题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
public class Solution {
public int TreeDepth(TreeNode root) {
int leftDepth = 0;
int rightDepth = 0;
if(root == null)
return 0;
if(root.left==null && root.right==null)
return 1;
if(root.left != null){
leftDepth = TreeDepth(root.left) + 1;
}
if(root.right != null){
rightDepth = TreeDepth(root.right) + 1;
}
return (rightDepth > leftDepth) ? rightDepth : leftDepth;
}
}
使用递归的方法,当root为null时,返回0;当root左右孩子都为null时,返回1;
更简化一点:
public class Solution {
public int TreeDepth(TreeNode root) {
int leftDepth = 0;
int rightDepth = 0;
if(root == null)
return 0;
leftDepth = TreeDepth(root.left) + 1;
rightDepth = TreeDepth(root.right) + 1;
return (rightDepth > leftDepth) ? rightDepth : leftDepth;
}
}
root为null时,返回0;不为null时,返回它的孩子长度+1;
import java.util.*;
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null)
return 0;
Queue<TreeNode> queue = new LinkedList();
TreeNode nlast = null;
TreeNode last = root;
int level = 0;
queue.offer(root);
while(!queue.isEmpty()){
TreeNode cur = queue.poll();
if(cur.left != null){
queue.offer(cur.left);
nlast = cur.left;
}
if(cur.right != null){
queue.offer(cur.right);
nlast = cur.right;
}
if(cur == last){
level++;
last = nlast;
}
}
return level;
}
}
注意:让last指向当前行的最后一个元素,nlast指向下一行的最后一个 元素,当当前元素cur和last相同的时候,说明当前行已经遍历到了最后一个,它的左右孩子也已经入队了,nlast也指向了下一行的最后一个元素,这时候让last指向nlast即可!
https://blog.youkuaiyun.com/xuchonghao/article/details/79405611
https://blog.youkuaiyun.com/Zheng548/article/details/65935030中有句话很好:求二叉树的深度,有:
1. 递归,这也是很多人非常容易想到的,递归实际也是深度优先的思想(DFS),时间复杂度为O(lgN),但是空间复杂度最坏为O(N),当二叉树退化为链表的时候。
2. 循环,这种方法不会有递归方法容易出现的栈溢出风险。循环其实是广度优先的思想(BFS)。时间复杂度O(N)