Create 104. Maximum Depth of Binary Tree.md

This commit is contained in:
唐树森 2018-11-01 14:49:37 +08:00 committed by GitHub
parent 82969c6409
commit 31511a8689
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,50 @@
# [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/)
# 思路
## 思路一: 递归
最简单的思路就是递归。若树非空,则树高就是: 1 + max(左子树高,右子树高),递归出口就是树为空。
## 思路二: 非递归
可考虑用层序遍历的方法计算树高。
用last指针表示每一层的最后一个节点每当遍历到这个节点即将树高加1并更新last指针。
last初始为root后面每当遍历完每层最后一个节点后即将last更新成下一层的最后一个节点为此需要用一个tmp来不断记录能确定的下一层的最右节点。
# C++
## 思路一
``` C++
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
else return 1 + max(maxDepth(root -> left), maxDepth(root -> right));
}
};
```
## 思路二
``` C++
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
int res = 0;
queue<TreeNode *>q;
TreeNode *p, *tmp=NULL, *last=root; // tmp用来更新last用
q.push(root);
while(!q.empty()){
p = q.front();
q.pop();
if(p -> left){
tmp = p -> left;
q.push(tmp);
}
if(p -> right){
tmp = p -> right;
q.push(tmp);
} // tmp记录了直到现在下一层最右的节点
if(p == last){ // 遇到了last
res++; // 树高加1
last = tmp; // 更新last
}
}
return res;
}
};
```