• 二叉树的遍历(循环方式)


    前序遍历(Preorder Traverse)

    根结点-左子树-右子树

    Java代码实现:

    public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> ret = new ArrayList<Integer>();
            if(root == null)
                return ret;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            while(cur != null || !stack.isEmpty()){
                if(cur != null){
                    ret.add(cur.val);
                    stack.push(cur);
                    cur = cur.left;
                }else{
                    TreeNode node = stack.pop();
                    cur = node.right;
                }
            }
            return ret;
        }

    后序遍历(postorder traverse)

    左子树-右子树-根结点

    代码实现:

    public List<Integer> postorderTraversal(TreeNode root) {
            LinkedList<Integer> ret = new LinkedList<Integer>();
            if(root == null)
                return ret;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            while(cur != null || !stack.isEmpty()){
                if(cur != null){
                    stack.push(cur);
                    ret.addFirst(cur.val);
                    cur = cur.right;
                }else{
                    TreeNode node = stack.pop();
                    cur = node.left;
                }
            }
            return ret;
        }

    中序遍历(inorder traverse):

    左子树-根结点-右子树

    代码实现:

     public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> ret = new ArrayList<Integer>();
            if(root == null)
                return ret;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            while(!stack.isEmpty() || cur != null){
                if(cur != null){
                    stack.push(cur);
                    cur = cur.left;
                }else{
                    TreeNode node = stack.pop();
                    ret.add(node.val);
                    cur = node.right;
                }
            }
            return ret;
        }
  • 相关阅读:
    《大道至简》读后感
    四大扩展欧几里得算法
    java8中使用函数式接口
    04_web基础(一)之tomcat介绍
    03_java基础(九)之综合练习与考核评估
    建站流程
    03_java基础(八)之static关键字与代码块
    (十)拒绝服务攻击工具包
    (九)拒绝服务攻击工具
    (八)拒绝服务–应用层DoS 攻击
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/8733110.html
Copyright © 2020-2023  润新知