您的位置:首页 > 其它

Maximum Depth of Binary Tree

2015-10-20 19:52 295 查看

题目: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.

思路:深搜

如果节点为空,返回0,;如果不为空,要看是否左右孩子节点是否存在,不存在直接返回1.
然后剩下有说明至少存在一个,左节点在,就定义left加上1.右节点同样处理。

代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//本质上方法一样,只是通过实践竟然不同
class Solution1 {
//https://leetcode.com/problems/maximum-depth-of-binary-tree/
public:
int maxDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
if(root->left==NULL&&root->right==NULL){
return 1;
}

int left=0;
if(root->left){
left=maxDepth(root->left)+1;
}

int right=0;
if(root->right){
right=maxDepth(root->right)+1;
}

return max(left,right);
}
};

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