[leetcode_104]Maximum Depth of Binary Tree

The problem is straightforward: given a binary tree, find its depth.

Got a Runtime Error once and a Compile Error once (due to redefinition in submitted code). Finally got Accepted.

For the RE, note that if root is NULL, you need to return 0 immediately. Otherwise, just use DFS.

Here is the code:

 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);
        }
    }
};