二叉树的深度

offer_38

概要:二叉树的深度

题目描述

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

思路:

  • 如果一棵树只有一个结点,那么它的深度为1;
  • 如果根结点只有左子树没有右子树,那么树的深度是左子树的深度加1,加1是加(当前结点)根节点这一层也就是当前结点下面没有结点了,就返回0,然后根据栈弹出,会加上当前这一层,这个+1 就是当前这一层
  • 如果既有左子树又有右子树,那么树的深度应该是左、右子树中深度较大的值再加1

代码实现:

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

参考链接:https://blog.csdn.net/YC1101/article/details/88377265?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

原文地址:https://www.cnblogs.com/SunAlbert/p/13489624.html