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

Sword finger offer 55 - I. depth DFS method of binary tree

2022-06-24 08:52:00 Mr Gao

The finger of the sword Offer 55 - I. The depth of the binary tree

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],

3

/
9 20
/
15 7

Return to its maximum depth 3 .
This question is very routine , But it is also very practical in programming , You can learn :

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
 
 int f(struct TreeNode* root){
    
     if(root){
    
         int a=f(root->left)+1;
         int b=f(root->right)+1;
        
         if(a>b){
    
             return a;
         }
         else{
    
             return b;
         }

     }
     else{
    
         return 0;
     }
 }


int maxDepth(struct TreeNode* root){
    
    return f(root);

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240628599908.html