Insert Node in a Binary Search Tree
Description
Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.
/**
* 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 static void main (String[] args){
TreeNode node1 = new TreeNode (2);
TreeNode node2 = new TreeNode (1);
TreeNode node3 = new TreeNode (4);
TreeNode node4 = new TreeNode (3);
node1.left = node2 ;
node1.right = node3 ;
node3.left = node4 ;
TreeNode node = new TreeNode(6) ;
TreeNode root = insertNode(node1, node) ;
print(root);
}
public static void print(TreeNode root){
if(root == null){
return ;
}
print(root.left);
System.out.print(root.val + " ");
print(root.right) ;
}
public static TreeNode insertNode(TreeNode root, TreeNode node) {
// write your code here
if (root == null){
return node ;
}
if(node.val < root.val ){
root.left = insertNode(root.left , node) ;
}else{
root.right = insertNode(root.right, node) ;
}
return root ;
}
}
这个博客讨论了如何在已有的二叉搜索树中正确插入一个新节点,以保持树的二叉搜索性质。提供的代码示例展示了如何递归地在树的左子树或右子树中找到合适的位置来插入新节点。
501

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



