广(宽)度优先搜索BFS & 深度优先搜索DFS & Leetcode Palindrome Partitioning (C++)
Same Tree (C++, Python)

Maximum Depth of Binary Tree (C++)

kitt posted @ 2013年9月24日 00:59 in LeetCode , 1361 阅读

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.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int maxDepth(TreeNode *root) {
        if (root == NULL) return 0;
        int left_depth = maxDepth(root->left);
        int right_depth = maxDepth(root->right);
        if (left_depth > right_depth)
            return left_depth + 1;
        else
            return right_depth + 1;
    }
};

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter