二叉搜索树的绝对最小值
作者:互联网
二叉搜索树的最小绝对差
给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。
1.采用非递归遍历二叉搜索树
1 public void midOrderTree(Node node){ 2 if (node == null) { 3 return; 4 } 5 Stack<Node> stack = new Stack<>(); 6 Node cur = node; 7 int res = node.getVal(); 8 int temp = 0; 9 while (cur != null || !stack.isEmpty()) { 10 while (cur != null){ 11 stack.push(cur); 12 cur = cur.getLeft(); 13 } 14 cur = stack.pop(); 15 res = Math.min(cur.getVal() - temp, res); 16 temp = cur.getVal(); 17 cur = cur.getRight(); 18 } 19 }
2.采用递归的方式来遍历得到一个顺序的数组,然后再求最小值。
1 private List<Integer> list = new ArrayList<>(); 2 public void midOrderTree3(Node node) { 3 if (node == null) { 4 return; 5 } 6 midOrderTree3(node.getLeft()); 7 list.add(node.getVal()); 8 midOrderTree3(node.getRight()); 9 } 10 11 public int getMinValue(List<Integer> list){ 12 if (list == null) { 13 return -1; 14 } 15 int m = 0; 16 for (int i = 1; i < list.size(); i++) { 17 m = Math.min(list.get(i) - list.get(i - 1), m); 18 } 19 return m; 20 }
标签:node,cur,getVal,int,list,二叉,最小值,搜索,null 来源: https://www.cnblogs.com/seedss/p/12995511.html