Java&Go-LeetCode701. 二叉搜索树中的插入操作-递归
- 算法
- 1.递归
- 2.当当前节点是null时,新建节点插入
- 3.当当前节点不是null时
- 如果插入值比当前节点值大,插入到右子节点
- 如果插入值比当前节点值小,插入到左子节点
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
} func insertIntoBST(root *TreeNode, val int) *TreeNode {
if root == nil {
root = &TreeNode{Val:val}
return root
}
if val < root.Val {
root.Left = insertIntoBST(root.Left, val)
} else {
root.Right = insertIntoBST(root.Right, val)
}
return root
} LeetCode题解 文章被收录于专栏
测试
