LeetCode题目
235.二叉搜索树的最近公共祖先
题目链接:Lowest Common Ancestor of a Binary Search Tree - LeetCode
代码如下:
递归法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root.Val > p.Val && root.Val > q.Val {
return lowestCommonAncestor(root.Left, p, q)
} else if root.Val < p.Val && root.Val < q.Val {
return lowestCommonAncestor(root.Right, p, q)
} else {
return root
}
}
迭代法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
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 nil
}
701.二叉搜索树中的插入操作
题目链接:Insert into a Binary Search Tree - LeetCode
代码如下:
递归法
/**
* 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 {
root = &TreeNode{Val: val}
return root
}
if root.Val > val {
root.Left = insertIntoBST(root.Left, val)
} else {
root.Right = insertIntoBST(root.Right, val)
}
return root
}
迭代法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func insertIntoBST(root *TreeNode, val int) *TreeNode {
cur := root
node := &TreeNode{
Val: val,
Left: nil,
Right: nil,
}
if cur == nil {
root = node
return root
}
var pre *TreeNode = nil
for cur != nil {
if cur.Val == val {
return root
}
pre = cur
if cur.Val < val {
cur = cur.Right
} else {
cur = cur.Left
}
}
if pre.Val < val {
pre.Right = node
} else {
pre.Left = node
}
return root
}
450.删除二叉搜索树中的节点
题目链接:Delete Node in a BST - LeetCode
代码如下:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func deleteNode(root *TreeNode, key int) *TreeNode {
if root == nil {
return root
}
if key < root.Val {
root.Left = deleteNode(root.Left, key)
return root
}
if key > root.Val {
root.Right = deleteNode(root.Right, key)
return root
}
if root.Left == nil {
return root.Right
}
if root.Right == nil {
return root.Left
}
cur := root.Right
for cur.Left != nil {
cur = cur.Left
}
cur.Left = root.Left
root = root.Right
return root
}