530. 二叉搜索树的最小绝对差
思路1:
那么二叉搜索树采用中序遍历,其实就是一个有序数组。
在一个有序数组上求两个数最小差值,这是不是就是一道送分题了。
最直观的想法,就是把二叉搜索树转换成有序数组,然后遍历一遍数组,就统计出来最小差值了。
思路2: 其实对于BST而言,如果不想先转换成增序数组的话,完全可以在中序遍历过程中 利用pre指针,进行逻辑处理。
思路3: 如下代码(自己原先想的思路)
public class Solution {
private int MinValue = Int32.MaxValue;//最值问题,需要全局变量
public int GetMinimumDifference(TreeNode root) {
if(root == null) return MinValue;
if(root.left != null)
{
int left = FindRightestNode(root.left);
int leftValue = GetMinimumDifference(root.left);
MinValue = leftValue < root.val - left ? leftValue : root.val - left;
}
if(root.right != null)
{
int right = FindLeftestNode(root.right);
int rightValue = GetMinimumDifference(root.right);
MinValue = rightValue < right - root.val ? rightValue : right - root.val;
}
return MinValue;
}
public int FindRightestNode(TreeNode node)
{
if(node.right == null) return node.val;//找到最右边节点的结束条件
return FindRightestNode(node.right);
}
public int FindLeftestNode(TreeNode node)
{
if(node.left == null) return node.val;//找到最左边节点的结束条件
return FindLeftestNode(node.left);
}
}
501. 二叉搜索树中的众数
思路: 二叉搜索树的中序遍历,记录pre节点。
public class Solution {
private TreeNode pre = null;
private int maxCount = 0;
private int count = 0;
private List<int> result = new List<int>();
public int[] FindMode(TreeNode root) {
InOrder(root);
return result.ToArray();
}
public void InOrder(TreeNode root) {
if(root == null) return;
InOrder(root.left);
if(pre == null)
{
count = 1;
} else if(root.val == pre.val) count++;
else count = 1;
pre = root;
if(count == maxCount)
{
result.Add(root.val);
}
if(count > maxCount)
{
maxCount = count;
result.Clear();
result.Add(root.val);
}
InOrder(root.right);
}
}
236. 二叉树的最近公共祖先
遇到这个题目首先想的是要是能自底向上查找就好了,这样就可以找到公共祖先了。
那么二叉树如何可以自底向上查找呢?
回溯啊,二叉树回溯的过程就是从低到上。
后序遍历(左右中)就是天然的回溯过程,可以根据左右子树的返回值,来处理中节点的逻辑。
思路:
假设存在于一边,那么另一边一定是null,那么哪个节点值先等于p或q,那这个节点就是祖先。
假设存在于两边,那么两边都不为null,那root就是祖先。
public class Solution {
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == p || root == q || root == null) return root;
TreeNode left = LowestCommonAncestor(root.left, p, q);
TreeNode right = LowestCommonAncestor(root.right, p, q);
if(left == null && right != null) return right;
else if(left != null && right == null) return left;
else if (left != null && right != null) return root;
else return null;
}
}