LeetCode 150 classic interview questions - the maximum depth of a binary tree (simple)

1. Question

Given a binary tree root, return its maximum depth.

The maximum depth of a binary tree is the number of nodes on the longest path from the root node to the furthest leaf node.

2.Example

 

 


 3. Ideas

depth first traversal

To query the maximum depth of a binary tree, you can change the problem to starting from the root node and checking the maximum depth of the left and right subtrees. If the depth of the left subtree is greater than the right subtree, return the depth of the left subtree. By analogy, the problem is split into sub-problems to determine the left and right subtrees of a certain node.

4.Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        // 最大深度算法
      if(root==null){
        return 0;
      }else{
          int left = maxDepth(root.left);
          int right =  maxDepth(root.right);
          // 当左右子树都遍历完成后返回最大节点并加上本身节点的深度
          return Math.max(left,right)+1;
      }
    }
}


 

おすすめ

転載: blog.csdn.net/dogxixi/article/details/132429093