版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解法一:递归
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return (left>right?left:right)+1;
}
}
解法二:非递归
思路: 借助层次遍历
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root==null) return 0;
ArrayList<TreeNode> list = new ArrayList<>();
int count = 0;
int low=0,high=0;
int tmphigh = high;
list.add(root);
while(low<=high){
TreeNode node = list.get(low);
if(node.left!=null){
list.add(node.left);
high++;
}
if(node.right!=null){
list.add(node.right);
high++;
}
low++;
if(low>tmphigh){
count++;
tmphigh = high;
}
}
return count;
}
}
解法三:非递归用队列
思路: 可节省空间复杂度
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public int TreeDepth(TreeNode pRoot) {
if(pRoot == null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(pRoot);
int depth = 0, count = 0, nextCount = 1;
while(queue.size()!=0){
TreeNode top = queue.poll();
count++;
if(top.left != null){
queue.add(top.left);
}
if(top.right != null){
queue.add(top.right);
}
if(count == nextCount){
nextCount = queue.size();
count = 0;
depth++;
}
}
return depth;
}
}