• LeetCode -- Binary Tree Postorder Traversal


    Question:

    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?

    Analysis:

    给出一棵二叉树,返回树的结点的后序遍历。

    Note:递归的解决方法是简单的,你能不用递归来实现吗?

    思路一:递归解决:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
     
        List<Integer> ll = new ArrayList<Integer>();
        public List<Integer> postorderTraversal(TreeNode root) {
            post(root);
            return ll;
        }
        
        public void post(TreeNode root) {
            if(root == null) return;
            if(root.left != null) post(root.left);
            if(root.right != null) post(root.right);
            ll.add(root.val);
        }
    }

    思路二:非递归解决。相较于二叉树的前序遍历和中序遍历,后续遍历更加复杂。当遍历完左子树还不能访问根结点,需要再遍历右子树。所以在我们的栈中,除了保存结点信息外还要说明目前遍历的结点是在是在上层根结点的左子树还是右子树中。

    首先使用栈暂存根结点的信息,然后向左子树遍历下去,此时根结点的flag为“L”。当访问完左子树中结点并从左子树退回时,还要去遍历根的右子树,此时更改根结点的flag为“R”。访问完右子树才能访问根结点的值。

    Answer:

    /**
     * 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> list = new ArrayList<Integer>();
            Stack<TreeNode> node = new Stack<TreeNode>();
            Stack<Integer> flag = new Stack<Integer>(); //1 means the left, 2 means the right.
            TreeNode p = root;
            do {
                while(p != null) {
                    node.push(p);
                    flag.push(1);
                    p = p.left;
                }
                boolean contin = true;
                while(contin && !node.isEmpty()) {
                    p = node.pop();
                    int f = flag.pop();
                    switch(f) {
                    case 1: f = 2; node.push(p); flag.push(f); contin = false; p = p.right; break;
                    case 2: list.add(p.val); break;
                    }
                }
            } while(!node.isEmpty());
            return list;
        }
    }
  • 相关阅读:
    Maximum sum
    走出迷宫
    取石子游戏
    全排列
    BZOJ3456 城市规划
    【SHOI2016】黑暗前的幻想乡
    【AHOI2012】信号塔
    HDU5730 Shell Necklace
    线性常系数齐次递推关系学习笔记
    矩阵树定理学习笔记
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5237507.html
Copyright © 2020-2023  润新知