当前位置:网站首页>Sword finger offer 55 - I. depth of binary tree

Sword finger offer 55 - I. depth of binary tree

2022-07-07 22:52:00 Yes' level training strategy

subject : Enter the root node of a binary tree , Find the depth of the tree . The nodes that pass from the root node to the leaf node ( Containing root 、 Leaf nodes ) A path to a tree , The length of the longest path is the depth of the tree .

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


Return to its maximum depth 3 .

The time for the person who will write this topic is estimated to be a few seconds .

It's actually intuitive , Want to calculate the depth of the tree , The direct idea is DFS, and DFS The realization of is to use recursion to realize perfectly .

The condition of recursive jump is very simple root == null, There is no doubt about this .

If not equal to null, Then the current node is a depth , Then add the depth of the larger of the two subtrees , Is the maximum depth of a real tree .

/** * 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;
        } 
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}

A simple question .

https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof

原网站

版权声明
本文为[Yes' level training strategy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130602332566.html