4.25
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
public TreeNode insertNode(TreeNode root, TreeNode node) {
// write your code here
if(root == null){
root = node;
return root;
}
if(node.val >= root.val){
if(root.right == null){
root.right = node;
}
else{
insertNode(root.right,node);
}
}
else{
if(root.left == null){
root.left = node;
}
else{
insertNode(root.left,node);
}
}
return root;
}
}
本文介绍了一种在二叉搜索树中插入新节点的方法。通过递归算法,确保了新节点按照二叉搜索树的规则正确放置。当节点值大于等于当前根节点值时,将其插入右子树;反之,则插入左子树。

2832

被折叠的 条评论
为什么被折叠?



