Binary Tree Postorder Traversal
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]
.
Note: Recursive solution is trivial, could you do it iteratively?
思路一:直接使用递归方法
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void postorder(TreeNode *root,vector<int> &data) { if(root==NULL) return; postorder(root->left,data); postorder(root->right,data); data.push_back(root->val); } vector<int> postorderTraversal(TreeNode *root) { vector<int> result; postorder(root,result); return result; } };
思路二:循环方法。后序遍历使用栈来做暂时的存储,而且树的后序遍历相对于树的前序遍历和中序遍历比较复杂,处理起来比较麻烦,一般这样我们都会使用一个pre变量来保存上次输出的结点,cur为当前结点,如果pre正好是cur的左子树或者右子树,那么可以输出cur,否则,说明还有cur的左子树或者右子树等待输出,也就是还没到cur输出的时候。另外cur没有左右子树即叶结点,可以输出。但是下面代码使用反向思维,先依次输出根结点->右子树结点->左子树结点,存到result,然后反转就是后序遍历的结果。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> result; if(root==NULL) return result; stack<TreeNode*> sTree; TreeNode *pCur=root; TreeNode *pPre=NULL; while(!sTree.empty()||pCur) { while(pCur!=NULL) { sTree.push(pCur); pCur=pCur->left; } pCur=sTree.top(); if(pCur->right==NULL||pCur->right==pPre) { result.push_back(pCur->val); pPre=pCur; sTree.pop(); pCur=NULL; } else pCur=pCur->right; } return result; } };
方向思维:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> result; if(root==NULL) return result; stack<TreeNode*> pTree; pTree.push(root); while(!pTree.empty()) { TreeNode *curNode=pTree.top(); result.push_back(curNode->val); pTree.pop(); if(curNode->left) pTree.push(curNode->left); if(curNode->right) pTree.push(curNode->right); } reverse(result.begin(),result.end()); return result; } };