题目描述:
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?
递归法就不说了,讲非递归法吧
用栈来存储,先存右孩子,再存左孩子,然后读取栈顶元素,如果取到节点的孩子左右孩子皆为空或者被访问过,就弹出栈,加入到结果中,否则继续将孩子节点放到栈中。
代码如下:
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
if(root==null)
return result;
stack.push(root);
Set<TreeNode> visited=new HashSet<TreeNode>();
while(!stack.isEmpty()){
TreeNode node=stack.peek();
if(node.right!=null&&!visited.contains(node.right))
stack.push(node.right);
if(node.left!=null&&!visited.contains(node.left))
stack.push(node.left);
if((node.left==null||visited.contains(node.left))&&(node.right==null||visited.contains(node.right))){
node=stack.pop();
result.add(node.val);
visited.add(node);
}
}
return result;
}
}
本文介绍了一种使用栈实现的二叉树后序遍历的非递归方法。通过先存储右子节点再存储左子节点的方式,并检查节点的子节点是否已被访问,从而实现了后序遍历。
311

被折叠的 条评论
为什么被折叠?



