zoukankan      html  css  js  c++  java
  • 二叉树的遍历

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

    先序遍历的结果为: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));
        }
    
    }
  • 相关阅读:
    PHP之数据库操作(一)
    PHP之字符串操作
    Subline使用方法
    POST和GET的区别(面试回答)
    面试题(1)
    http协议
    JS 闭包(内存溢出与内存泄漏)(垃圾回收机制)
    JS----事件机制 事件冒泡 事件捕获 事件委托
    js的数据类型、判断对象类型 js对象
    JS----DOM节点操作:创建 ,插入,删除,复制,查找节点
  • 原文地址:https://www.cnblogs.com/hemoely/p/4858965.html
Copyright © 2011-2022 走看看