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.

题目:

给定二叉树,找到它的最大深度。

最大深度是从根节点到最远叶节点的最长路径上的节点数。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
       if (root == null){
           return 0;
       }
        int maxLeft = maxDepth(root.left);
        int maxRight = maxDepth(root.right);
        return maxLeft>maxRight?maxLeft+1:maxRight+1;
    }
}

本题主要用到递归,但首先要判断结点为空的时候,接下来判断左右结点的长度,选出最大的深度

猜你喜欢

转载自blog.csdn.net/wo8vqj68/article/details/85713808
今日推荐