LeetCode Binary Tree PostorderTranversal
Problem Description
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?
Problem Solution
1. 递归方案
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<int> nodeVec; public: void traverse(TreeNode *root){ if(root==NULL) return; traverse(root->left); traverse(root->right); nodeVec.push_back(root->val); } vector<int> postorderTraversal(TreeNode *root) { traverse(root); return nodeVec; } };
2. 非递归方案
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<int> nodeVec; public:void iterTraverse(TreeNode *root){ if(root==NULL) return; stack<TreeNode*> st; TreeNode *pCur,*pPrev=NULL; //pCur: current tree node, pPrev: previous visited tree node st.push(root); while(!st.empty()) { pCur=st.top(); if((pCur->left == NULL && pCur->right == NULL) || (pPrev != NULL && (pCur->left==pPrev || pCur->right==pPrev))) { nodeVec.push_back(pCur->val); pPrev=pCur; st.pop(); } else { if(pCur->right != NULL) st.push(pCur->right); if(pCur->left != NULL) st.push(pCur->left); } } } vector<int> postorderTraversal(TreeNode *root) { iterTraverse(root); return nodeVec; } };
作者:ballwql
本文为作者原创,版权所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。