vector<int> postorderTraversal(TreeNode *root) {
     vector<int> answer;
     stack<stackNode> emptyStack;
     fullStack.swap(emptyStack);
     if (root == NULL)
     {
         return answer;
     }
     fullStack.push(stackNode(root, 0));
     while(!fullStack.empty())
     {
         stackNode currNode = fullStack.top();
         fullStack.pop();
         if (currNode.state == 0)
         {
             fullStack.push(stackNode(currNode.node, 1));
             if (currNode.node->right != NULL)
             {
                 fullStack.push(stackNode(currNode.node->right, 0));
             }
             if (currNode.node->left != NULL)
             {
                 fullStack.push(stackNode(currNode.node->left, 0));
             }
         }
         else
         {
             answer.push_back(currNode.node->val);
         }
     }
     return answer;
 }
示例#2
0
void sort_stack(stack<int>& s) {
	stack<int> r;

	while (!s.empty()) {
		int tmp = s.top();
		s.pop();
		while (!r.empty() && r.top() < tmp) {
			s.push(r.top());
			r.pop();
		}
		r.push(tmp);
	}
	s.swap(r);
}
示例#3
0
void sort_stack(stack<T>& s)
{
    stack<T> helper;
    while (s.size() > 0) {
        T t = s.top();
        s.pop();
        if (helper.empty() || t >= helper.top()) {
            helper.push(t);
            continue;
        }
        
        while (helper.size() > 0) {
            T h = helper.top();
            if (t >= h) {
                break;
            }
            s.push(h);
            helper.pop();
        }
        helper.push(t);
    }
    s.swap(helper);
}
示例#4
0
    int maxDepth(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
		stack<StateNode> tmp;
		treeStack.swap(tmp);
		int maxHeight = 0;
		if (root != NULL)
		{
		StateNode initState;
		initState.height = 1;
		initState.treeNode = *root;
        treeStack.push(initState);
        while(!treeStack.empty())
        {
            StateNode sNode = treeStack.top();
			if (sNode.height > maxHeight)
			{
				maxHeight = sNode.height;
			}
			treeStack.pop();
            if (sNode.treeNode.left != NULL)
			{
				StateNode newNode;
				newNode.height = sNode.height + 1;
				newNode.treeNode = *sNode.treeNode.left;
				treeStack.push(newNode);
			}
            if (sNode.treeNode.right != NULL)
			{
				StateNode newNode;
				newNode.height = sNode.height + 1;
				newNode.treeNode = *sNode.treeNode.right;
				treeStack.push(newNode);
			}
        }
		}
        return maxHeight;
    }