Categories
不学无术

LeetCode #104. Maximum Depth of Binary Tree

题目:https://leetcode.com/problems/maximum-depth-of-binary-tree/
思路:就是个树遍历的东西,很简单地可以用递归实现
代码:

/**
 * 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) {
        // Left - N - Right
        if(root == NULL) {
            return 0;
        } else {
            //Non-empty
            int leftDeep = 1 + maxDepth(root->left);
            int rightDeep = 1 + maxDepth(root->right);
            if(leftDeep > rightDeep)
                return leftDeep;
            else
                return rightDeep;
        }
    }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.