LeetCode題解專欄:LeetCode題解
我做的所有的LeetCode的題目都放在這個專欄裏,大部分題目Java和Python的解法都有。
題目地址:Maximum Depth of Binary Tree - LeetCode
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its depth = 3.
這道題目意思很容易懂,就是求樹的高度,最簡單的做法是用遞歸。
Python解法如下:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root==None:
return 0
return 1 +max(self.maxDepth(root.left),self.maxDepth(root.right))
遞歸的缺點是調用了很多次,使用迭代更快,使用迭代的話就要使用隊列了。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
stack = []
if root is not None:
stack.append((1, root))
depth = 0
while stack != []:
current_depth, root = stack.pop()
if root is not None:
depth = max(depth, current_depth)
stack.append((current_depth + 1, root.left))
stack.append((current_depth + 1, root.right))
return depth
C++解法如下:
/**
* 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) {
if(root == nullptr){
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};