您的位置:首页 > 其它

leetcode 之Binary Tree Postorder Traversal

2016-05-26 17:47 344 查看
题目描述:

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]
.

即 给定一颗二叉树。 使用后序遍历输出。 不用递归的方式。

首先递归的方式:后续遍历的话先访问左子树,然后访问右子树,然后访问根节点。

# 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]
"""
res = []
if not root:
return res
self.get(root, res)
return res

def get(self, root, res):
if root.left:
self.get(root.left, res)
if root.right:
self.get(root.right, res)
res.append(root.val)


非递归的思想是,需要向左找到叶子节点,并将节点依次放入栈中,并标记这些节点的左子树已经被访问了一次了。然后判断叶子节点的右子树是否存在,如果叶子节点右子树存在,继续向左找到叶子节点。。。并标记该节点的右子树已经访问过了。

代码如下:

# 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]
"""
res = []
tmp = []
flag = []  // 右子树被访问标记
flag1 = [] // 左子树被访问标记
if not root:
return res
tmp.append(root)
while tmp:
while root.left and root not in flag1:
tmp.append(root.left)
flag1.append(root)
root = root.left
node = tmp[-1]
if  node not in flag:
if node.right:
tmp.append(node.right)
flag.append(node)
root = node.right
continue
else:
root = tmp.pop()
res.append(root.val)
else:
root = tmp.pop()
res.append(root.val)
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: