Golang Leetcode 701. Insert into a Binary Search Tree.go

2019-04-29 18:02:53 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1419693

思路

如果插入值大于根节点,插入右子树

反之插入左子树

code

代码语言:javascript复制
type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func insertIntoBST(root *TreeNode, val int) *TreeNode {

	if root == nil {
		return &TreeNode{
			Val: val,
		}
	}
	if val > root.Val {
		root.Right = insertIntoBST(root.Right, val)
	} else {
		root.Left = insertIntoBST(root.Left, val)
	}
	return root

}

0 人点赞