• Leecode 145. 二叉树的后序遍历


    给定一个二叉树,返回它的 后序 遍历。

    示例:

    输入: [1,null,2,3]  
       1
        
         2
        /
       3 
    
    输出: [3,2,1]

    进阶: 递归算法很简单,你可以通过迭代算法完成吗?

    import java.util.Stack;
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            ArrayList<Integer> res = new ArrayList();
            if(root==null) return res;
            Stack<TreeNode> st = new Stack();
            while(!st.isEmpty()||root!=null){
                while(root!=null) {
                    st.add(root);
                    res.add(root.val);
                    root = root.right;  //先遍历右节点
                }
                root = st.pop();
                root =root.left;        //再左节点
            }
            Collections.reverse(res);   //反转链表
            return res;
    
        }
    }

    递归:

    class Solution {
        List<Integer> res = new ArrayList<>();
        public List<Integer> postorderTraversal(TreeNode root) {
            deal(root);
            return res;
        }
    
        public void deal(TreeNode root){
            if(root==null) return;
            deal(root.left);
            deal(root.right);
            res.add(root.val);
        }
    }
  • 相关阅读:
    栈的实现方式
    复合和继承
    循环链表和双向链表
    抽象类和接口
    private构造器和单例模式
    内部类
    关于初始化和清理
    多态的理解
    幾個小知識
    Youth
  • 原文地址:https://www.cnblogs.com/kpwong/p/14651195.html
Copyright © 2020-2023  润新知