有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。 给定二叉树的根节点root,请返回所求距离。
真是醉了,看漏了叶子节点。
代码:
1 import java.util.*; 2 3 /* 4 public class TreeNode { 5 int val = 0; 6 TreeNode left = null; 7 TreeNode right = null; 8 public TreeNode(int val) { 9 this.val = val; 10 } 11 }*/ 12 public class Tree { 13 14 private TreeNode maxNode; 15 private TreeNode minNode; 16 17 private boolean stop = false; 18 private int result; 19 20 public int getDis(TreeNode root) { 21 if(root == null) { 22 return 0; 23 } 24 25 maxNode = root; 26 minNode = root; 27 28 getMaxAndMin(root); 29 getMaxLength(root); 30 return result; 31 } 32 33 private int[] getMaxLength(TreeNode root) { 34 35 if(root == null) 36 return new int[] {-1, -1}; 37 if(root == maxNode) 38 return new int[] {0, -1}; 39 if(root == minNode) 40 return new int[] {-1, 0}; 41 42 int[] left = getMaxLength(root.left); 43 int[] right = getMaxLength(root.right); 44 45 int[] curResult = new int[]{Math.max(left[0], right[0]), Math.max(left[1], right[1])}; 46 47 if(curResult[0] != -1) 48 curResult[0]++; 49 if(curResult[1] != -1) 50 curResult[1]++; 51 52 if(!stop && curResult[0] != -1 && curResult[1] != -1) { 53 result = curResult[0] + curResult[1]; 54 stop = true; 55 } 56 57 return curResult; 58 } 59 60 private void getMaxAndMin(TreeNode root) { 61 62 if(root == null) 63 return; 64 if(root.left == null && root.right == null) { 65 if(root.val < minNode.val) { 66 minNode = root; 67 } 68 if(root.val > maxNode.val) { 69 maxNode = root; 70 } 71 } 72 getMaxAndMin(root.left); 73 getMaxAndMin(root.right); 74 75 } 76 }
时间: 2024-09-29 05:31:47