题目链接
层序遍历
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int getMinimumDifference(TreeNode root) {ArrayList<Integer> array = new ArrayList<>();Deque<TreeNode> queue = new LinkedList<TreeNode>();if(root == null){return 0;}queue.offer(root);while(!queue.isEmpty()){TreeNode node = queue.poll();array.add(node.val);if(node.left != null){queue.offer(node.left);}if(node.right != null){queue.offer(node.right);}}// 使用 Collections.sort(array) 对 ArrayList 进行排序Collections.sort(array);int min = Integer.MAX_VALUE;for(int i = 1; i < array.size(); i++){min = Math.min(min, array.get(i) - array.get(i - 1));}return min;}
}
在 Java 中,不能使用 array.sort() 的原因是 ArrayList 类没有直接提供 sort() 方法。应该使用Collections.sort() 或 List.sort() 方法对列表进行排序。
中序遍历
做麻烦了,二叉搜索树中序遍历可以直接得到有序序列!!!!
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {ArrayList<Integer> array = new ArrayList();public int getMinimumDifference(TreeNode root) {traversal(root);if(array.size() < 2){return 0;}int min = Integer.MAX_VALUE;for(int i = 1; i < array.size(); i++){min = Math.min(min,array.get(i) - array.get(i - 1));}return min;}public void traversal(TreeNode root){if(root == null){return;}traversal(root.left);array.add(root.val);traversal(root.right);}
}