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

总结

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

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

相关推荐
柠檬少少开发11 分钟前
图像拼接算法及实现(一)
人工智能·算法·计算机视觉
weixin_486681141 小时前
C++系列-STL容器中统计算法count, count_if
开发语言·c++·算法
一道秘制的小菜1 小时前
C++第七节课 运算符重载
服务器·开发语言·c++·学习·算法
咕噜咕嘟嘟嘟2 小时前
343. 整数拆分
数据结构·算法
WenGyyyL3 小时前
力扣最热一百题——二叉树的直径
java·c++·算法·二叉树·深度优先
sdlkjaljafdg3 小时前
vector<bool>性能测试
开发语言·c++·算法
muyierfly3 小时前
36.贪心算法3
算法·贪心算法
Kenneth風车4 小时前
【机器学习(七)】分类和回归任务-K-近邻 (KNN)算法-Sentosa_DSML社区版
人工智能·算法·低代码·机器学习·分类·数据分析·回归
m0_631270406 小时前
标准C++(二)
开发语言·c++·算法
沫刃起6 小时前
Codeforces Round 972 (Div. 2) C. Lazy Narek
数据结构·c++·算法