Maximum Depth of Binary Tree
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.
Analysis:
This is an easy problem.Either DFS (depth first search) or BFS(breadth first search).
Details see source code.
C++: DFS
Python: BFS
Code(C++):
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root){return 0;}
else{
return max(maxDepth(root->right)+1,maxDepth(root->left)+1);
}
}
};
Code(Python):
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root == None:
return 0
q = []
q.append([root, 1])
res = 0
while len(q) != 0:
node, dep = q.pop()
res = max(res, dep)
if node.left != None:
q.append([node.left, dep + 1])
if node.right != None:
q.append([node.right, dep + 1])
return res
No comments:
Post a Comment