zoukankan      html  css  js  c++  java
  • 剑指38.二叉树的深度

    题目描述

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

    思路

    思路1:采用递归实现。树的深度=max(左子树深度,右子树深度)+1。
     
    思路2:层序遍历。
     

    解法1

    /**
     public class TreeNode {
     int val = 0;
     TreeNode left = null;
     TreeNode right = null;
    
     public TreeNode(int val) {
     this.val = val;
    
     }
    
     }
     */
    public class Solution {
        public int TreeDepth(TreeNode root) {
            if (root == null)
                return 0;
            // 分别得到root左右孩子的深度
            int left = TreeDepth(root.left);
            int right = TreeDepth(root.right);
            return Math.max(left,right) + 1;
        }
    }

    解法2

    import java.util.*;
    //BFS的层次遍历思想,记录二叉树的层数,
    //遍历完,层数即为最大深度
    public class Solution {
        public int TreeDepth(TreeNode root) {
            if(root == null) return 0;
            int depth = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                int levelNums = queue.size();//先获取本层的节点数,然后遍历
                depth++;
                for(int i = 0; i < levelNums; i++){
                    TreeNode cur = queue.poll();
                    if(cur.left != null) queue.offer(cur.left);
                    if(cur.right != null) queue.offer(cur.right);
                }
            }
            return depth;
        }
    }
     
  • 相关阅读:
    英语俚语里的gotta和gonna
    如何设置Win XP远程登录如何远程控制电脑
    C#中as与is的用法(收藏)
    just用法
    even用法
    up to用法小结
    go out with用法
    realize与recognize辨析
    go through用法
    堆优先队列
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/13549308.html
Copyright © 2011-2022 走看看