zoukankan      html  css  js  c++  java
  • 剑指offer——二叉树深度

    二叉树的深度

    输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    }
    

      

    注意:树的深度,是要求最长的树高,即要找到所有的叶子结点

    java中的选择两数中的最大值,要用Math.max(a, b)

    public class Solution {
        public int TreeDepth(TreeNode root) {
            return getDeep(root, 0);
        }
        
        public int getDeep(TreeNode root, int len){
            if(root == null) return 0;
            if(root.left == null && root.right == null){
                return len + 1;
            }
            return 1 + Math.max(getDeep(root.left, len), getDeep(root.right, len));
        }
    }
    

      

    看了别人的代码后,改进自己的方法

    public class Solution {
        public int TreeDepth(TreeNode root) {
            if(root == null) return 0;
            return 1 + Math.max(TreeDepth(root.left), TreeDepth(root.right));
        }
    }
    

    别人的非递归方法

      

    采用层序遍历,每读取一层,level++.

    同时采取队列保存上一层的所有节点

    队列要用实现了队列接口的类来完成,如LinkedList  等

    剑指offer——栈与队列相关 Queue,Deque,Stack

    import java.util.Queue;
    import java.util.LinkedList;
    public class Solution {
        public int TreeDepth(TreeNode root) {
            if(root == null) return 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int level = 0;
            while(queue.peek() != null){
                int preCount = queue.size();
                while((preCount--) != 0){
                    TreeNode node = queue.poll();
                    if(node.left != null){
                        queue.offer(node.left);
                    }
                    if(node.right != null){
                        queue.offer(node.right);
                    }
                }
                level++;
            }
            return level;
        }
    }
    

      

  • 相关阅读:
    tpshop添加后台菜单
    TPshop添加后台菜单
    TPshop隐藏index.php
    TPshop表结构
    TPshop下载安装
    django学习2 视图和模板
    java 运行时常量、编译时常量、静态块执行顺序
    java 比较几种常见循环方式的优劣
    linux下svn命令大全
    linux为用户配置java环境变量
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8630915.html
Copyright © 2011-2022 走看看