代码随想录算法训练营|day22

第六章 二叉树

235.二叉搜索树的最近公共祖先

递归 :如果p,q 位于root 的两侧,返回root;否则必然同大于root.Val同小于root.Val,用p.Val或q.Val来判断,第一次满足递归终止条件的即为父亲节点。

复制代码
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	if (root.Val - p.Val) * (root.Val - q.Val) <= 0 {
        return root
    }
    if root.Val < p.Val {
        return lowestCommonAncestor(root.Right, p, q)
    }else {
        return lowestCommonAncestor(root.Left, p, q)
    }
}

迭代

复制代码
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
    for root != nil {
        if root.Val > p.Val && root.Val > q.Val {
            root = root.Left
        } else if root.Val < p.Val && root.Val < q.Val {
            root = root.Right
        } else {
            return root
        }
    }
    return root
}

701.二叉搜索树中的插入操作

递归:找到val满足二叉搜索数性质的空节点位置直接插入。

复制代码
func insertIntoBST(root *TreeNode, val int) *TreeNode {
    node := &TreeNode{Val:val}
    if root == nil {
        return node
    }
    if root.Val < val {
        root.Right = insertIntoBST(root.Right, val)
    }else if root.Val > val {
        root.Left = insertIntoBST(root.Left, val)
    }
    return root
}

迭代 :找到待插入节点的位置【parent】,与当前节点值比较插入

复制代码
func insertIntoBST(root *TreeNode, val int) *TreeNode {
    node := &TreeNode{Val:val}
    if root == nil {
        return node
    }
    cur := root
    parent := cur
    for cur != nil {
        parent = cur
        if cur.Val > val {
            cur = cur.Left
        }else {
            cur = cur.Right
        }
    }
    if val > parent.Val {
        parent.Right = node
    }else{
        parent.Left = node
    }
    return root
}

450.删除二叉搜索树中的节点

递归 :找到待删除节点,判断当前节点,若无左子树返回root.Right;若无右子树,返回root.Left,否则将当前节点的左子树添加到右子树最左节点【树的最小位置】下,返回root.Right。

复制代码
func deleteNode(root *TreeNode, key int) *TreeNode {
    if root == nil {
        return root
    }
    if key > root.Val {
        root.Right = deleteNode(root.Right, key)
    }else if key < root.Val {
        root.Left = deleteNode(root.Left, key)
    }else{
        if root.Left == nil {
            return root.Right
        } 
        if root.Right == nil {
            return root.Left
        }
        node := root.Right
        for node.Left != nil {
            node = node.Left
        }
        node.Left = root.Left
        root = root.Right
    }
    return root
}

代码随想录文章详解

235.二叉搜索树的最近公共祖先
701.二叉搜索树中的插入操作
450.删除二叉搜索树中的节点

总结

二叉搜索树中的插入操作 看题目要求以为得旋转树,去瞅瞅平衡二叉树旋转树那部分

对于二叉树的理解终于到了看山不是山的境界了

相关推荐
岁忧41 分钟前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_78944 分钟前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说3 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy3 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特5 小时前
每日mysql
数据结构·算法
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
lifallen6 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest6 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
EndingCoder6 小时前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法
丶小鱼丶6 小时前
链表算法之【合并两个有序链表】
java·算法·链表