530.二叉搜索树的最小绝对差
方法一
二叉搜索树中序遍历就是有序数组,所以可以利用这个性质将其转变为有序数组再进行操作
方法二
引入最大值和最小值,类似于检查是否为二叉搜索树一样
func getMinimumDifference(root *TreeNode) int {
vec := make([]int, 0)
travel(root, &vec)
if len(vec) < 2 {return 0}
ret := math.MaxInt64
for i := 1; i < len(vec); i++{
ret = int(math.Min(float64(ret), float64(vec[i] - vec[i - 1])))
}
return ret
}
func travel(node *TreeNode, input *[]int){
if node == nil{
return
}
travel(node.Left, input)
*input = append(*input, node.Val)
travel(node.Right, input)
}
class Solution {
public:
long long int getmin(TreeNode* root,long long int lower, long long int upper){
long long int left = abs(root->val - lower);
long long int right = abs(root->val - upper);
if(root->left){
left = min(left,getmin(root->left,lower,root->val));
}
if(root->right){
right = min(right,getmin(root->right,root->val,upper));
}
return min(left,right);
}
int getMinimumDifference(TreeNode* root) {
return getmin(root,INT_MIN,INT_MAX);
}
};
501.二叉搜索树中的众数
二叉搜索树中的众数
如果是普通的二叉树,直接遍历然后记录到map中即可。
因为是二叉搜索树,所以中序遍历时是有序的,因此只需要查看前后两个点即可,所以用上了cur和prev双指针。当count=max时,添加进去,当count大于时,res清空然后再重新加进去。
func findMode(root *TreeNode) []int {
res := make([]int, 0)
count := 1
max := 1
var prev *TreeNode
var travel func(node *TreeNode)
travel = func(node *TreeNode){
if node == nil {return}
travel(node.Left)
if prev != nil &&prev.Val == node.Val{
count++
}else {
count = 1
}
if count >= max {
if count > max && len(res) > 0{
res = []int{node.Val}
}else{
res = append(res, node.Val)
}
max = count
}
prev = node
travel(node.Right)
}
travel(root)
return res
}
236. 二叉树的最近公共祖先
二叉树的最近公共祖先
“那么二叉树如何可以自底向上查找呢?
回溯啊,二叉树回溯的过程就是从低到上。
后序遍历(左右中)就是天然的回溯过程,可以根据左右子树的返回值,来处理中节点的逻辑。” --------代码随想录
当左右都有值的时候,就说明该节点就是中间节点,否则只把左值或者右值传递上去
还有一种简单粗暴的方法就是把p和q的路径给记录到数组中,求交叉的节点就可以了
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil { return nil }
if root.Val == p.Val || root.Val == q.Val{
return root
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left != nil && right != nil{
return root
}
if left != nil{
return left
}
if right != nil{
return right
}
return nil
}