您的位置:首页 > 其它

[LeetCode]Maximum Depth of Binary Tree

2015-07-22 13:58 375 查看
简洁都是相对了,看看我第二遍解此题的java代码
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}


-----------------------第一遍解题思路------------
解题思路:
其实这题很简单,就是深度搜索,每个node都返回自己的depth即可。
但是由于这次写dfs代码的时候,写的更加简练,所以我决定记录下来

/**
* 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) {

return dfs(root);
}

int dfs(TreeNode *root){
if (root == NULL){
return 0;
}
return max(dfs(root->left), dfs(root->right)) + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: