[leetcode_104]Maximum Depth of Binary Tree

题意很简单,给一颗二叉树,请问该树的深度。
RE一次,CE一次[提交代码重定义]
最后AC
RE需要注意的是:root如果是NULL需要直接返回0;
其他DFS即可。
附上代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    int depth;
    int maxDepth(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(root == NULL)
            return 0;
        depth = 1;
        query(root,1);
        return depth;
    }
    void query(TreeNode *node,int k)
    {
        if(node->left == NULL && node->right == NULL)
        {
            if(k > depth)
                depth = k;
        }
        if(node->left != NULL)
        {
            query(node->left,k+1);
        }
        if(node->right != NULL)
        {
            query(node->right,k+1);
        }
    }
};
Licensed under CC BY-NC-SA 4.0