Easily understandable solution with procedure of thinking


  • 0
    X
    class Solution {
    public:
        int maxDepth(TreeNode* root) {
        	if(root == null)return 0;
            int len_left = maxDepth(root->left);
            int len_right = maxDepth(root->right);
            return max(len_left, len_right) + 1;
        }
    };
    

    My procedure with think is that:

    1. I suppose that there are two function that already done and will return the max length of the two subtree(represented with two triangles). Suppose that they called left() and right(). And store the result in len_left and len_right respectively.
      img1
      http://imgur.com/ETNTywN
    2. So we can get the max length by get max(len_left, len_right) + 1.
    3. Now we put back the maxDepth to left() and right().
    4. Add the terminal condition. You can take a simple tree as example to think.
      img2
      http://imgur.com/ShxmZo2
      Sorry that the image can be displayed, I have tried several image host but fail.

  • 0
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.