方法如下
package com.wxl.DichotomizationTree.thinking;
import com.wxl.DichotomizationTree.Node.Node;
public class Depth {
public int minDepth1(Node head){
if(head == null ) return 0;
return process(head,1);
}
private int process(Node cur, int level) {
if (cur.left==null && cur.right==null){
return level;
}
int ans = Integer.MAX_VALUE;
if (cur.left != null){
ans = Math.min(process(cur.left,level+1),ans);
}
if (cur.right != null){
ans = Math.min(process(cur.right,level+1),ans);
}
return ans;
}
public static void main(String[] args){
Node head = createTree();
Depth depth = new Depth();
System.out.println("最小深度为:"+depth.minDepth1(head));
}
private static Node createTree() {
Node head = new Node(0);
Node leftHead = head;
Node rightHead = head;
head.left = new Node(1);
head.right = new Node(2);
leftHead = leftHead.left;
leftHead.left = new Node(3);
leftHead.right = new Node(4);
rightHead = rightHead.right;
rightHead.left = new Node(5);
rightHead.right = new Node(6);
return head;
}
}
遍历二叉树的神级方法