530. Minimum Absolute Difference in BST
- 思路
- 中序遍历递归
-
java class Solution { int res = Integer.MAX_VALUE; TreeNode pre = null; public int getMinimumDifference(TreeNode root) { if ( root == null){ return 0; } helper(root); return res; } private void helper( TreeNode root){ if (root == null){ return; } helper(root.left); if (pre != null){ res = Math.min (res, root.val - pre.val); } pre = root; helper(root.right); } }
- 迭代
-
java class Solution { TreeNode pre; Stack stack; public int getMinimumDifference(TreeNode root) { if (root == null){ return 0; } stack = new Stack<>(); TreeNode temp = root; int res = Integer.MAX_VALUE; while( temp != null || !stack.isEmpty()){ if ( temp != null){ stack.push(temp); temp = temp.left; }else{ temp = stack.pop(); if(pre != null){ res = Math.min(res, temp.val - pre.val); } pre = temp; temp = temp.right; } } return res; } }
501. Find Mode in Binary Search Tree
- 思路
- BST就是中序遍历
-
java class Solution { List res; Integer maxCount; Integer count; TreeNode pre; public int[] findMode(TreeNode root) { res = new ArrayList<>(); maxCount = 0; count = 0; helper(root); int [] result = new int[res.size()]; for(int i = 0; i < result.length; i++){ result[i] = res.get(i); } return result; } private void helper(TreeNode root){ if (root == null){ return; } helper(root.left); if(pre != null && root.val == pre.val){ count ++; }else{ count = 1; } if (count > maxCount){ maxCount = count; res.clear(); res.add(root.val); }else if (count == maxCount){ res.add(root.val); } pre = root; helper(root.right); } }
236. Lowest Common Ancestor of a Binary Tree
- 思路
-
java class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { return helper(root, p, q); } private TreeNode helper( TreeNode root, TreeNode p, TreeNode q){ if (root == null){ return root; } if(root == p || root == q){ return root; } TreeNode left = helper( root.left, p, q); TreeNode right = helper(root.right, p, q); if (left != null && right != null){ return root; } if (left == null && right != null){ return right; } else if (right == null && left !=null){ return left; }else{ return null; } } }
-