The maximum depth of the binary tree computing leetcode.104

Description Title : for a binary tree, the binary tree returns the maximum depth

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.

Ideas:

Recursive, starting from the root, to get the root of the left subtree and right subtree depth, whichever is greater then +1, then got the greatest depth of the tree

Boundary conditions: the current node has a sub-tree, then recursively, otherwise the maximum depth of the current sub-tree

Recursive forward segment: the current node has children, then recursively

Recursive return segments: the current node has no children

 

Code:

 

/ ** 
 * A for binary Tree Node Definition. 
 * Public class the TreeNode { 
 * int Val; 
 * the TreeNode left; 
 * the TreeNode right; 
 * the TreeNode (int X) {X = Val;} 
 *} 
 * / 

class Solution {
     public  int maxDepth (TreeNode root) {
         // ideas
         // recursive:
         // from the root starting to get depth of the node the left subtree and right subtree, whichever is greater +1, for the deepest depth
         // boundary conditions: whether the current node there are child nodes, there continues recursively down, did not return
         // recursive forward segment: the current node has children
         // recursive return segments: single sign node has no children
         // return 1+ Math.max (maxDepth (root .left), maxDepth (root.right))
         ;// returns the current node's left and right subtrees great depth that add a depth of 1, to obtain the depth of each node
         // finally time to get back to the root of the deepest depth 
        
        IF (root == null ) return 0 ;
         return +. 1 Math.max (maxDepth (root.left), maxDepth (root.right)); 
        
    } 
}

 

Guess you like

Origin www.cnblogs.com/smallone/p/12117935.html