Leetcode 104 level 0

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.

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

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.


Answer:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root){
            return 0;
        }
        if (root->left==NULL && root->right==NULL){
            return 1;
        }
        else{
            int left_num = 0, right_num = 0;
            if(root->left!=NULL){
                left_num = maxDepth(root->left)+1;
            }
            if(root->right!=NULL){
                right_num = maxDepth(root->right)+1;
            }
            return max(right_num,left_num);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/shit_kingz/article/details/79993768
104