题目
题目链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
题目解析:
二叉搜索树的概念:对于树中的每一个结点,他的左子树都要比他这个结点要小,对于他的右子树的结点都要比他要大。所以对一个二叉树进行中序遍历,如果是单调递增的,则可以说明这个树是二叉搜索树。
所以题目很简单就可以解决,判断,如果比结点大就往右走,比结点小就往左走。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null)
return new TreeNode(val);
if(val>root.val)
root.right = insertIntoBST(root.right,val);
else
root.left = insertIntoBST(root.left,val);
return root;
}
}