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

[sword finger offer] 55 - I. depth of binary tree

2022-07-01 13:39:00 LuZhouShiLi

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

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 .

Ideas

  Nodes have both left and right subtrees , Then the depth of the tree is the larger value of the depth of the left and right subtrees plus 1.

Code

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
    
public:
    int maxDepth(TreeNode* root) {
    
        if(root == nullptr)
        {
    
            return 0;
        }

        int left = maxDepth(root->left);
        int right = maxDepth(root->right);

        return (left > right) ? (left + 1) :(right + 1);

    }
};
原网站

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