标签:
https://leetcode.com/problems/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]
.
解题思路:
后序遍历的迭代方式,比前序和中序都要复杂一点。一般,是使用两个stack去操作。
开始和inorder相同,重点在于,如果当前栈顶节点的右子树为空,或者,它的右节点已经被遍历过,才能将栈顶节点弹出,加入结果,并且将其标志为遍历过。
否则,就要将root置为栈顶节点的右子树,继续迭代。也就是对先处理栈顶节点的右子树。
这样才能实现 left - right - root 的顺序。
这里写了一个形式上简单点的方法,只用了一个stack。和前序、中序也较为统一,方便一起记忆。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); if(root == null) { return result; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode pre = null; while(root != null || stack.size() > 0) { if(root != null) { stack.push(root); root = root.left; } else { TreeNode peek = stack.peek(); if(peek.right != null && pre != peek.right) { // stack.push(peek.right); root = peek.right; } else { peek = stack.pop(); result.add(peek.val); pre = peek; } } } return result; } }
Binary Tree Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4511430.html