给定一颗二叉树的头节点head
求以head为头的树中,最小深度是多少?
public class MinHeight {
public static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
val = x;
}
}
public static void main(String[] args) {
TreeNode h1 = new TreeNode(1);
TreeNode h2 = new TreeNode(2);
TreeNode h3 = new TreeNode(3);
TreeNode h4 = new TreeNode(4);
TreeNode h5 = new TreeNode(5);
TreeNode h6 = new TreeNode(6);
h1.left = h2;
h2.left = h3;
h3.left = h4;
h4.left = h6;
h1.right = h5;
System.out.println(minDepth1(h1));
System.out.println(minDepth2(h1));
}
// 下面的方法是一般解,使用递归
public static int minDepth1(TreeNode head){
if(head == null){
return 0;
}
return p(head);
}
// 返回x为头的树,最小深度是多少
public static int p(TreeNode x){
if(x.left == null && x.right == null){
return 1;
}
// 左右子树起码有一个不为空
int leftH = Integer.MAX_VALUE;
if(x.left != null){
leftH = p(x.left);
}
int rightH = Integer.MAX_VALUE;
if(x.right != null){
rightH = p(x.right);
}
return 1 + Math.min(leftH,rightH);
}
// 下面的方法是morris遍历的解, 比递归节省空间
public static int minDepth2(TreeNode head) {
if (head == null){
return 0;
}
TreeNode cur = head;
TreeNode mostRight = null;
int curLevel = 0;
int minHeight = Integer.MAX_VALUE;
while(cur != null){
mostRight = cur.left;
if(mostRight != null){
int rightBoardSize = 1;
while(mostRight.right != null && mostRight.right != cur){
rightBoardSize++;
mostRight = mostRight.right;
}
if(mostRight.right == null){// 第一次到达
curLevel++;
mostRight.right = cur;
cur = cur.left;
continue;
}else{ // 第二次到达
if(mostRight.left == null){
// 上个节点是叶子节点
minHeight = Math.min(minHeight,curLevel);
}
curLevel = curLevel - rightBoardSize;
mostRight.right = null;
}
}else{
curLevel++;
}
cur = cur.right;
}
int findRight = 1;
cur = head;
while(cur.right != null){
findRight++;
cur = cur.right;
}
if(cur.left == null && cur.right == null){
minHeight = Math.min(minHeight,findRight);
}
return minHeight;
}
}