二叉树遍历思想(三) : 后序遍历

  二叉树的后序遍历递归定义 : 

  1) 当前节点为空(null)直接返回

  2) 对于非空节点

    i)   后序遍历左子树

    ii)  后序遍历右子树

    iii) 操作当前节点

  二叉树的非递归遍历方法 : 

    使用栈来进行遍历。

    策略简述 : 

      利用两层循环嵌套(但时间复杂度仍然是O(N)),策略注释在代码中。

 1 class Solution {
 2     public List<Integer> postorderTraversal(TreeNode root) {
 3         List<Integer> list = new ArrayList<Integer>();
 4         if (root == null)
 5             return list;
 6         
 7         Stack<TreeNode> stack = new Stack<TreeNode>();
 8         TreeNode top = null, last = null;
 9         // 对于该循环有两种状态 : 
10         // 第一种是 root != null,表示要后续遍历输出root
11         // 第二种是 root == null,表示要输出栈顶元素的右子树再输出栈顶。
12         while (root != null || !stack.isEmpty()){
13             // 将遍历到当前树的最左叶子节点处。
14             // 也就是将第一种状态转换为第二种状态。
15             while (root != null){
16                 stack.push(root);
17                 root = root.left;
18             }
19             
20             top = stack.peek(); // 此时以top为根的树的左子树已经后续遍历结束了。
21             
22             // 如若top的右子树为Null,或者上次已经输出了top的右子树。
23             // 只有在这种情况下(左右子树都已经输出了)才开始输出
24             if (top.right == null || top.right == last){
25                 stack.pop();
26                 list.add(top.val); // 操作top当前层根节点
27                 last = top; // 标记上一次输出为top
28             }else{
29                 root = top.right; // 后序遍历top的右子树。
30             }
31         }
32         return list;
33     }
34 }

猜你喜欢

转载自www.cnblogs.com/vizdl/p/12287866.html