Binary Tree Postorder Traversal

题目描述:

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;
    }
}


你可能感兴趣的:(java,LeetCode,tree,迭代,后序遍历)