原题链接:145. Binary Tree Postorder Traversal
【思路-Java、Python】-非递归实现
以[1,2,3,4,5,null,6]为例,需要用到一个栈,具体执行过程如下图所示:
stack 取出的节点值是从 res 的头部插入的,这点与二叉树的前序遍历、中序遍历存在不同:
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> res = new ArrayList<Integer>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
if (temp != null) {
res.add(0, temp.val);
stack.add(temp.left);
stack.add(temp.right);
}
}
return res;
}
}
67 / 67
test cases passed. Runtime: 2 ms Your runtime beats 7.50% of javasubmissions.
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = []
stack.append(root)
res = []
while stack :
temp = stack.pop()
if temp :
res.append(temp.val)
stack.append(temp.left)
stack.append(temp.right)
return res[::-1]
67 / 67
test cases passed. Runtime: 40 ms Your runtime beats 67.45% of pythonsubmissions.
【补充-Python】-递归实现
递归方法很简单,一般都能想到,这里也就不赘述了,用 Python 的递归实现
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def dfs(root, res) :
if root :
dfs(root.left, res)
dfs(root.right, res)
res.append(root.val)
dfs(root, res)
return res
67 / 67
test cases passed. Runtime: 40 ms Your runtime beats 67.45% of pythonsubmissions.