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: vector<int> postorderTraversal(TreeNode *root) { vector<int> result; postOrder(root, result); return result; } void postOrder(TreeNode *node, vector<int>& result){ if(node==NULL){ return; } postOrder(node->left, result); postOrder(node->right, result); result.push_back(node->val); } };
/** * 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; stack<TreeNode*> s; //最终结果栈 stack<TreeNode*> sLeftNode; //左孩子栈 TreeNode* node=root; while(node!=NULL||!sLeftNode.empty()){ if(node!=NULL){ s.push(node); if(node->left!=NULL){ sLeftNode.push(node->left); } node=node->right; }else{ node=sLeftNode.top(); sLeftNode.pop(); } } while(!s.empty()){ node=s.top(); result.push_back(node->val); s.pop(); } return result; } };
[LeetCode] Binary Tree Postorder Traversal
原文地址:http://blog.csdn.net/kangrydotnet/article/details/44887859