[LeetCode]第十七题 :树的深度

题目描述:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

题目解释:

给出一个二叉树,求其深度。

深度是指从根节点到叶子节点路径最长的节点数。

注意:叶子结点是指没有孩子节点的节点。

题目解法:

1.我的解法:树肯定要用递归。首先,先判断树是否为空,空的话就返回0,否则要递归求出左子树的深度和右子树的深度,返回其中最深的子树深度 + 1就是这个树的深度。代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        else{
            int leftHigh = maxDepth(root.left);
            int rightHigh = maxDepth(root.right);
            if(leftHigh > rightHigh) return 1 + leftHigh;
            else return 1 + rightHigh;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80903189