剑指offer-----二叉树的深度

1、题目描述

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

2、思想

如果一棵树只有一个节点,那么它的深度是1。

如果根节点只有左子树而没有右子树,那么树的深度就应该是其左子树的深度加1。

如果根节点只有右子树而没有左子树,那么树的深度就应该是其右子树的深度加1。

如果根节点既有右子树又有左子树,那么树的深度就是其左、右子树深度的较大值再加1。

3、代码

/**
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;
}
int left = 0;
if(root.left != null){
left = TreeDepth(root.left);
}
int right = 0;
if(root.right != null){
right = TreeDepth(root.right);
}
return left>right?left+1:right+1;
        
    }
}

猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/80876579
今日推荐