文章目录
  1. 1. Maximum Depth of Binary Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

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.

思路

max(左分支高度,右分支高度)+1
队列,BFS

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 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)
return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};

Python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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):
Depth=0
if not root:
return 0
queue=[]
queue.append(root)
count=len(queue)
while len(queue)!=0:
tmp=queue[0]
del queue[0]
count=count-1
if tmp.left:
queue.append(tmp.left)
if tmp.right:
queue.append(tmp.right)
if count==0:
Depth+=1
count=len(queue)
return Depth

文章目录
  1. 1. Maximum Depth of Binary Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题