1、前言
题目描述2、思路
还是使用二叉搜索树的框架,大于 val 只向左搜索,小于 val 值向右搜索。
3、代码
/**
* 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){
return new TreeNode(val);
}
if(val < root.val){
root.left = insertIntoBST(root.left, val);
}else{
root.right = insertIntoBST(root.right, val);
}
return root;
}
}
网友评论