catch-up
This commit is contained in:
42
insert-into-a-binary-search-tree/sol.go
Normal file
42
insert-into-a-binary-search-tree/sol.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
return &TreeNode{
|
||||
Val: val,
|
||||
}
|
||||
}
|
||||
node := &TreeNode{
|
||||
Val: val,
|
||||
}
|
||||
current := root
|
||||
for {
|
||||
if val < current.Val {
|
||||
if current.Left == nil {
|
||||
current.Left = node
|
||||
return root
|
||||
}
|
||||
current = current.Left
|
||||
} else {
|
||||
if current.Right == nil {
|
||||
current.Right = node
|
||||
return root
|
||||
}
|
||||
current = current.Right
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user