题目:
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.
又双叒是一道之前水过的题,但是重点在于,这道题终于是我现在自己就能写出来的题目了感动!题目要求一棵树的最大高度,只有根节点的树的高度为1,那么就可以采用递归,递归基是当这个节点为NULL时返回0,否则就在它的左右子树中选择最大的高度+1就是以这个节点为根的树的最大高度。递归版本代码如下,运行时间8ms,只打败了3%……内存1.3M,打败96%……
/**
* 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_depth = 0;
if (root == NULL) {
return 0;
}
else {
max_depth = max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
return max_depth;
}
};
另外一种方法是BFS,采用迭代的方法写。数据结构需要使用queue而不是stack,刚开始在这里被卡了一下不知道为什么要用queue,print出来看了一下发现queue是BFS,而stack是DFS,queue的话因为先进先出,所以push进去的子节点会等先push进去的父节点被pop以后才被处理,但是stack的话是子节点刚被push进去又被pop出来了,所以是DFS。但是昨天的两道题里面,queue和stack都是一样的,具体还没思考为什么,感觉应该是因为昨天那两道题只需要比较是否相同,不管怎样的顺序都可以。先把根节点push进queue,然后当queue不为空的时候遍历整个queue,每遍历一次就相当于是一层,queue存的就相当于这一层里面的每个节点,然后对queue中的每个节点进行向下搜索,如果有它的子节点就push进queue中。这里需要注意在for循环里面,queue的size是动态变化的,因此需要提前把它拎出来作为一个原始的变量。代码如下,运行时间4ms,打败97%,内存同样是1.3M:
/**
* 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*