701. 二叉搜索树中的插入操作

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
利用二叉树的性质。
添加的值 > 当前节点的值:在右子树添加
添加的值 < 当前节点的值:在左子树添加
添加的值 < 当前节点的值:不做任何操作。
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) {
return new TreeNode(val);
}
if(root.val < val) {
root.right = insertIntoBST(root.right, val);
} else if(root.val > val) {
root.left = insertIntoBST(root.left, val);
} else {
// 相等的时候,什么也不做。
}
return root;
}
浙公网安备 33010602011771号