您的位置:首页 > 其它

145、Binary Tree Postorder Traversal

2015-11-29 11:08 381 查看
题目:

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?
解题思路:
树的后续遍历

c++版本:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void gotoHLVFLS(stack<TreeNode*>& s){
while(TreeNode* x=s.top()){
if(x->left)
{
if(x->right)
s.push(x->right);
s.push(x->left);
}
else
s.push(x->right);
}
s.pop();
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
if(root)s.push(root);
while(true){
if(s.empty())break;
if(root!=s.top()->left and root!=s.top()->right)
gotoHLVFLS(s);
root = s.top();s.pop();
res.push_back(root->val);
}
return res;
}
};


python 版本:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def gotoHLVFS(s):
x = s[-1]
while(x):
if(x.left!=None):
if(x.right!=None):
s.append(x.right)
s.append(x.left)
else:
s.append(x.right)
x = s[-1]
s.pop()
stack,res = [],[]
if(root!=None):stack.append(root)
while(True):
if(len(stack)==0):break
if(root!=stack[-1].left and root!=stack[-1].right):
gotoHLVFS(stack)
root = stack.pop()
res.append(root.val)
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: