104. Maximum Depth of Binary Tree
2016-11-21 18:20
92 查看
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.
思路:這題本來要用DFS解的,寫著寫著不知道為啥用了backtracking.......
class Solution {
public:
int _maxDepth;
int maxDepth(TreeNode* root) {
if(root == NULL) {
return 0;
}
int curDepth = 0;
solve(root, curDepth);
return _maxDepth;
}
void solve(TreeNode* tree, int& currentDepth) {
if(tree == NULL) {
_maxDepth = std::max(_maxDepth, currentDepth);
return;
}
currentDepth += 1;
solve(tree->left, currentDepth);
solve(tree->right, currentDepth);
currentDepth -= 1;
}
};
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路:這題本來要用DFS解的,寫著寫著不知道為啥用了backtracking.......
class Solution {
public:
int _maxDepth;
int maxDepth(TreeNode* root) {
if(root == NULL) {
return 0;
}
int curDepth = 0;
solve(root, curDepth);
return _maxDepth;
}
void solve(TreeNode* tree, int& currentDepth) {
if(tree == NULL) {
_maxDepth = std::max(_maxDepth, currentDepth);
return;
}
currentDepth += 1;
solve(tree->left, currentDepth);
solve(tree->right, currentDepth);
currentDepth -= 1;
}
};
相关文章推荐
- 【遍历二叉树】01二叉树的前序遍历【Binary Tree Preorder Traversal】
- leetcode[145]:Binary Tree Postorder Traversal
- Java [Leetcode 257]Binary Tree Paths
- 【二叉查找树】03验证是否为二叉查找树【Validate Binary Search Tree】
- LeetCode Convert Sorted List to Binary Search Tree
- Invert Binary Tree
- 【Leetcode】235. Lowest Common Ancestor of a Binary Search Tree
- leetcode 226 Invert Binary Tree 翻转二叉树
- Binary Tree Postorder Traversal
- [LeetCode]Balanced Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree
- 【LeetCode笔记】Construct Binary Tree from Inorder and Postorder Traversal 中序、后序遍历求二叉树
- Leetcode: Maximum Depth of Binary Tree 理解分析
- Full Binary Tree Picture hiho一下第 177 周
- [leedcode 114] Flatten Binary Tree to Linked List
- #93 Balanced Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- LeetCode--Binary Tree Level Order Traversal
- LeetCode(Binary Tree Level Order Traversal, 2,Zigzag)二叉树的层次遍历