701.二叉搜索树中的插入操作
思路:
- 如果val值大于root值,则到右子树寻找,如果val值小于root值,则到左子树寻找
- 当执行到 root==null 时,说明应该插入这个节点中,即这就是递归终止条件
代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
root = new TreeNode(val);
return root;
}
if (val > root.val) {
root.right = insertIntoBST(root.right, val);
} else if (val < root.val) {
root.left = insertIntoBST(root.left, val);
}
return root;
}
}