LeetCode 145:Binary Tree Postorder Traversal(后序遍历)

来源:互联网 发布:cisco网络交换机型号 编辑:程序博客网 时间:2024/09/21 09:05

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [3,2,1].

题目要求对二叉树进行非递归的后序遍历,所谓后序遍历即,先访问左子树、然后是右子树,最后访问根节点。通常采用递归的方法,题目要求采用非递归的方法实现。算法如下:

1)如果根节点非空,将根节点加入到栈中。

2)如果栈不空,取栈顶元素(暂时不弹出),

                             如果(左子树已访问过或者左子树为空),且(右子树已访问过或右子树为空),则弹出栈顶节点,将其值加入数组,

                            如果左子树不为空,切未访问过,则将左子节点加入栈中,并标左子树已访问过。

                            如果右子树不为空,切未访问过,则将右子节点加入栈中,并标右子树已访问过。

3)重复第二步,直到栈空。

//包裹结构体 struct TreeNodeWrapper{struct TreeNode *pNode;bool lVisited;bool rVisited;TreeNodeWrapper(TreeNode * p){pNode = p; lVisited= false; rVisited= false;}}; class Solution {public:    vector<int> postorderTraversal(TreeNode* root) {vector<int> result;stack<TreeNodeWrapper*> node_stack;if (root == NULL){return result;}node_stack.push(new TreeNodeWrapper(root));while(!node_stack.empty()){TreeNodeWrapper* pNode = node_stack.top();if ((!pNode->pNode->left ||pNode->lVisited ) && ( !pNode->pNode->right||pNode->rVisited)){                             //左右子树都已访问过                                node_stack.pop();result.push_back(pNode->pNode->val);delete pNode;}else{                               if (!pNode->lVisited && pNode->pNode->left){//左子树不为空,且未访问过,则访问左子树node_stack.push(new TreeNodeWrapper(pNode->pNode->left));pNode->lVisited = true;}else{if (pNode->pNode->right){                                             //右子树不为空,且未访问过                                               node_stack.push(new TreeNodeWrapper(pNode->pNode->right));pNode->rVisited = true;}}}}return result;}    };





1 0
原创粉丝点击