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

总结

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

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

相关推荐
Univin1 小时前
C++(10.5)
开发语言·c++·算法
Asmalin2 小时前
【代码随想录day 35】 力扣 01背包问题 一维
算法·leetcode·职场和发展
剪一朵云爱着2 小时前
力扣2779. 数组的最大美丽值
算法·leetcode·排序算法
qq_428639612 小时前
虚幻基础:组件间的联动方式
c++·算法·虚幻
深瞳智检2 小时前
YOLO算法原理详解系列 第002期-YOLOv2 算法原理详解
人工智能·算法·yolo·目标检测·计算机视觉·目标跟踪
怎么没有名字注册了啊3 小时前
C++后台进程
java·c++·算法
Rubisco..3 小时前
codeforces 2.0
算法
未知陨落3 小时前
LeetCode:98.颜色分类
算法·leetcode
~kiss~4 小时前
K-means损失函数-收敛证明
算法·机器学习·kmeans
杨小码不BUG4 小时前
Davor的北极探险资金筹集:数学建模与算法优化(洛谷P4956)
c++·算法·数学建模·信奥赛·csp-j/s