leetcode 104

一个简单的递归,回朔时候可以求出从各个叶子到当前根的最大长度.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode* root) {
13         if(root==NULL)return 0;
14         int a=maxDepth(root->left)+1;
15         int b=maxDepth(root->right)+1;
16         return a>b?a:b;
17     }
18 };

 

posted @ 2016-07-21 10:08  HYDhyd  阅读(77)  评论(0编辑  收藏  举报