235. 二叉搜索树的最近公共祖先
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if p.Val > q.Val {
return lowestCommonAncestor(root, q, p)
}
rootVal := root.Val
lVal := p.Val
rVal := q.Val
if lVal <= rootVal && rootVal <= rVal {
return root
}
if rootVal > rVal {
return lowestCommonAncestor(root.Left, p, q)
}
return lowestCommonAncestor(root.Right, p, q)
}
701.二叉搜索树中的插入操作
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func insertIntoBST(root *TreeNode, val int) *TreeNode {
if root == nil {
node := TreeNode{Val: val}
return &node
}
if val > root.Val { // turn right
root.Right = insertIntoBST(root.Right, val)
} else { // <. turn left
root.Left = insertIntoBST(root.Left, val)
}
return root
}
450.删除二叉搜索树中的节点
扫描二维码,在手机上阅读
推荐阅读:
收藏