代码随想录算法训练营|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.删除二叉搜索树中的节点

总结

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

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

相关推荐
茉莉玫瑰花茶2 分钟前
算法 --- 字符串
算法
博笙困了12 分钟前
AcWing学习——差分
c++·算法
NAGNIP15 分钟前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP16 分钟前
大模型微调框架之LLaMA Factory
算法
echoarts16 分钟前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客22 分钟前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法
徐小夕26 分钟前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
小刘鸭地下城38 分钟前
深入浅出链表:从基础概念到核心操作全面解析
算法
小刘鸭地下城1 小时前
哈希表核心精要:从 O(1) 原理到链式地址与开放寻址
算法
BenChuat1 小时前
Java常见排序算法实现
java·算法·排序算法