在二叉查找树中插入节点
来源:互联网 发布:斗牛seo官网 编辑:程序博客网 时间:2024/05/17 06:06
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
2 2 / \ / \1 4 --> 1 4 / / \ 3 3 6
/**
* 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 = new TreeNode(node.val);
return root;
}
else if(root.val>node.val){
root.left = insertNode(root.left,node);
return root;
}
else{
root.right = insertNode(root.right,node);
return root;
}
}
}
* 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 = new TreeNode(node.val);
return root;
}
else if(root.val>node.val){
root.left = insertNode(root.left,node);
return root;
}
else{
root.right = insertNode(root.right,node);
return root;
}
}
}
【非递归】
public TreeNode insertNode(TreeNode root, TreeNode node) {
// write your code here
if(root == null)
{ root = new TreeNode(node.val);
return root;
}
TreeNode temp = root;
while(temp!=null){
if(temp.val>node.val){
if(temp.left==null){
temp.left = node;
return root;
}
else
temp = temp.left;
}
else{
if(temp.right==null){
temp.right = node;
return root;
}
else
temp = temp.right;
}
}
return root;
}
// write your code here
if(root == null)
{ root = new TreeNode(node.val);
return root;
}
TreeNode temp = root;
while(temp!=null){
if(temp.val>node.val){
if(temp.left==null){
temp.left = node;
return root;
}
else
temp = temp.left;
}
else{
if(temp.right==null){
temp.right = node;
return root;
}
else
temp = temp.right;
}
}
return root;
}
0 0
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- Android .9.png图片的制作与使用
- MVC DateTable 直接显示在页面上
- maven的配置for Windows
- android中的文件操作详解以及内部存储和外部存储
- Android 自定义视图总结
- 在二叉查找树中插入节点
- centos 下 mariadb 表不区分大小写
- 安装PlistBuddy
- 我写过代码
- Excel 生成随机数,随机日期,随机字符串
- AndroidMPAndroidChart饼状图
- 基于官方文档的matplotlib简介
- idea用maven打包
- oracle查看创建了哪些存储过程