|
| 1 | +package com.imooc.activiti.helloworld; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.LinkedList; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Queue; |
| 10 | + |
| 11 | +/** |
| 12 | + * @author shironghui on 2019/4/18. |
| 13 | + */ |
| 14 | +class Solution13 { |
| 15 | + |
| 16 | + List<Integer> list=new ArrayList<>(); |
| 17 | + public int minDiffInBST(TreeNode root) { |
| 18 | + int min=Integer.MAX_VALUE; |
| 19 | + dfs(root); |
| 20 | + for (int i=1;i<list.size();i++){ |
| 21 | + min=Math.min(min,list.get(i)-list.get(i-1)); |
| 22 | + } |
| 23 | + return min; |
| 24 | + } |
| 25 | + |
| 26 | + //中序遍历二叉搜索树,list列表有序 |
| 27 | + private void dfs(TreeNode root) { |
| 28 | + if(root==null) { |
| 29 | + return; |
| 30 | + } |
| 31 | + dfs(root.left); |
| 32 | + list.add(root.val); |
| 33 | + dfs(root.right); |
| 34 | + } |
| 35 | + |
| 36 | +} |
| 37 | + |
| 38 | +public class TestBinaryTree4 { |
| 39 | + public static TreeNode stringToTreeNode(String input) { |
| 40 | + input = input.trim(); |
| 41 | + input = input.substring(1, input.length() - 1); |
| 42 | + if (input.length() == 0) { |
| 43 | + return null; |
| 44 | + } |
| 45 | + |
| 46 | + String[] parts = input.split(","); |
| 47 | + String item = parts[0]; |
| 48 | + TreeNode root = new TreeNode(Integer.parseInt(item)); |
| 49 | + Queue<TreeNode> nodeQueue = new LinkedList<>(); |
| 50 | + nodeQueue.add(root); |
| 51 | + |
| 52 | + int index = 1; |
| 53 | + while(!nodeQueue.isEmpty()) { |
| 54 | + TreeNode node = nodeQueue.remove(); |
| 55 | + |
| 56 | + if (index == parts.length) { |
| 57 | + break; |
| 58 | + } |
| 59 | + |
| 60 | + item = parts[index++]; |
| 61 | + item = item.trim(); |
| 62 | + if (!item.equals("null")) { |
| 63 | + int leftNumber = Integer.parseInt(item); |
| 64 | + node.left = new TreeNode(leftNumber); |
| 65 | + nodeQueue.add(node.left); |
| 66 | + } |
| 67 | + |
| 68 | + if (index == parts.length) { |
| 69 | + break; |
| 70 | + } |
| 71 | + |
| 72 | + item = parts[index++]; |
| 73 | + item = item.trim(); |
| 74 | + if (!item.equals("null")) { |
| 75 | + int rightNumber = Integer.parseInt(item); |
| 76 | + node.right = new TreeNode(rightNumber); |
| 77 | + nodeQueue.add(node.right); |
| 78 | + } |
| 79 | + } |
| 80 | + return root; |
| 81 | + } |
| 82 | + |
| 83 | + public static void main(String[] args) throws IOException { |
| 84 | + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); |
| 85 | + String line; |
| 86 | + while ((line = in.readLine()) != null) { |
| 87 | + TreeNode root = stringToTreeNode(line); |
| 88 | + |
| 89 | + int ret = new Solution13().minDiffInBST(root); |
| 90 | + |
| 91 | + String out = String.valueOf(ret); |
| 92 | + |
| 93 | + System.out.print(out); |
| 94 | + } |
| 95 | + } |
| 96 | +} |
0 commit comments