leetcodeOJ 104. Maximum Depth of Binary Tree
2017-03-27 15:48
204 查看
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 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) {
int max = 0;
int* p = &max;
maxDpt(root, 0, p);
return max;
}
private:
void maxDpt(TreeNode* root, int dep, int* p){
if(root==NULL){
return;
}
dep++;
if(!root->left && !root->right){
if(*p < dep){
*p = dep;
// cout<<*p<<endl;
}
}
maxDpt(root->left, dep, p);
maxDpt(root->right, dep, p);
dep--;
}
};
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
最大深度问题,注意要引用传递
/**
* 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) {
int max = 0;
int* p = &max;
maxDpt(root, 0, p);
return max;
}
private:
void maxDpt(TreeNode* root, int dep, int* p){
if(root==NULL){
return;
}
dep++;
if(!root->left && !root->right){
if(*p < dep){
*p = dep;
// cout<<*p<<endl;
}
}
maxDpt(root->left, dep, p);
maxDpt(root->right, dep, p);
dep--;
}
};
相关文章推荐
- sicily 1156 Binary tree
- 用二叉链表实现完全二叉树 (Linked Complete Binary Tree) 的实现(二)
- poj2499--Binary Tree
- 关于算法面试中涉及Binary Tree的问题
- 【原创】leetCodeOj ---Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- 【原创】leetCodeOj --- Majority Element 解题报告(脍炙人口的找n个元素数组中最少重复n/2次的元素)
- LeetCodeOJ刷题之15-16【3Sum(三数和问题)】
- LeetCodeOJ. Longest Common Prefix
- [Leetcode] binary tree 右视问题
- LeetCodeOJ——Word Search
- 104. Maximum Depth of Binary Tree
- LeetCodeOJ:338. Counting Bits
- [HDOJ5573]Binary Tree(找规律,贪心)
- 【规律】【贪心】【数学】HDU 5573 Binary Tree
- LeetCode:Binary Tree Traversal(二叉树遍历非递归)
- LeetCode之Invert Binary Tree(Java版)
- leetcode解题报告:104. Maximum Depth of Binary Tree
- hdu 5573 Binary Tree【脑洞构造】
- 104. Maximum Depth of Binary Tree
- leetcode-104. Maximum Depth of Binary Tree