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

题目描述

题解

DFS

大致思路为将当前根节点的值与要插入的值比较, 如果要插入的值比根节点的值大, 那么要将值传递给右子树的根节点. 如果右子树为null, 那么直接new一个新的节点作为右儿子. 反之亦然

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}

if (val < root.val) {
if (root.left == null){
root.left = new TreeNode(val);
}else {
root.left = insertIntoBST(root.left, val);
}
}else {
if (root.right == null){
root.right = new TreeNode(val);
}else {
root.right = insertIntoBST(root.right, val);
}
}

return root;
}
}
-------------本文结束感谢您的阅读-------------
可以请我喝杯奶茶吗