• 二叉树的遍历


    二叉树结点的定义与先序(中左右)、中序(左中右)、后序(左右中)遍历,顺便写个最大深度,都是递归实现,之后再学习非递归的方法。

    先序遍历的结果为:5,2,4,1,3,8,4,2,9,中序遍历的结果:4,2,1,5,4,8,2,3,9,后序遍历结果:4,1,2,4,2,8,9,3,5。

    package leetcode;
    
    class TreeNode
    {
        TreeNode left;
        TreeNode right;
        int val;
        TreeNode(int val)
        {
            this.val = val;
        }
        static int getDepth(TreeNode root)
        {
            if(root==null)
            {
                return 0;
            }
            int right = getDepth(root.right);
            int left = getDepth(root.left);
            return left>right?left+1:right+1;
        }
        static void scanNodes(TreeNode root)
        {
            if(root==null)
            {
                return;
            }
            //System.out.println(root.val); //先序遍历
            scanNodes(root.left);
            //System.out.println(root.val); //中序遍历
            scanNodes(root.right);
            System.out.println(root.val); //后序遍历
        }
        public static void main(String[] args)
        {
            TreeNode root = new TreeNode(5);
            TreeNode left1 = new TreeNode(2);
            TreeNode left2 = new TreeNode(1);
            TreeNode left3 = new TreeNode(4);
            TreeNode right1 = new TreeNode(3);
            TreeNode right2 = new TreeNode(8);
            TreeNode right3 = new TreeNode(9);
            TreeNode right4 = new TreeNode(4);
            TreeNode right5 = new TreeNode(2);
            root.left = left1;
            left1.right = left2;
            left1.left = left3;
            root.right = right1;
            right1.left = right2;
            right1.right = right3;
            right2.left = right4;
            right2.right = right5;
            scanNodes(root);
            System.out.println("The depth of BinaryTree is: "+getDepth(root));
        }
    
    }
  • 相关阅读:
    全球覆盖 哈希
    陌上花开 模板 三维偏序
    洛谷 P4556 [Vani有约会]雨天的尾巴 /【模板】线段树合并
    熟练剖分(tree) 树形DP
    那一天她离我而去 二进制分组建图
    平凡的函数 线性筛积性函数
    wmz的数数(数状数组)
    跳一跳 概率与期望
    洛谷 P4284 [SHOI2014]概率充电器 概率与期望+换根DP
    SpringBoot手动事务参考链接
  • 原文地址:https://www.cnblogs.com/hemoely/p/4858965.html
Copyright © 2020-2023  润新知