标签:
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?
二叉树的后序遍历
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int>res; if(root==NULL) return res; return postorder(root,res); } vector<int> postorder(TreeNode* root,vector<int>& res) { if(root) { postorder(root->left,res); postorder(root->right,res); res.push_back(root->val); } return res; } };
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int>res; if(root==NULL) return res; stack<TreeNode*> qu; TreeNode* node=root; while(!qu.empty()||node) { if(node) { qu.push(node); res.push_back(node->val); node=node->right; } else { TreeNode* cur=qu.top(); qu.pop(); node=cur->left; } } reverse(res.begin(),res.end()); return res; } };
leetcode--Binary Tree Postorder Traversal
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45622309