在二叉查找树中插入节点
来源:互联网 发布:淘宝助理创建宝贝教程 编辑:程序博客网 时间:2024/06/03 05:08
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
样例
需要保证该树仍然是一棵二叉查找树。
注意事项
You can assume there is no duplicate values in this tree + node.
样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
import java.util.Scanner;/** * * 给定一棵二叉查找树和一个新的树节点,将节点插入到树中。需要保证该树仍然是一棵二叉查找树。 注意事项You can assume there is no duplicate values in this tree + node.样例给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的: 2 2 / \ / \1 4 --> 1 4 / / \ 3 3 6 * @author Dell * */public class Test85 {public static TreeNode CreatTree(TreeNode t) { Scanner sc=null; sc=new Scanner(System.in); t=creatNode(t,sc); return t; } public static TreeNode creatNode(TreeNode t, Scanner sc) { String temp=sc.next();if(temp.trim().equals("#")){return null;}else{t=new TreeNode(Integer.parseInt(temp));t.left=creatNode(t.left,sc);t.right=creatNode(t.right,sc);return t;}}//非递归public static TreeNode insertNode(TreeNode root, TreeNode node) { if(root==null) { root=node; return root; } if(node==null) return root; TreeNode p=root; TreeNode q=null; int flag=-1; while(p!=null) { if(p.val>node.val) { if(p.left==null) { q=p; flag=0; } p=p.left; } else if(p.val<node.val) { if(p.right==null) { q=p; flag=1; } p=p.right; } } if(flag==0) q.left=node; if(flag==1) q.right=node; return root;}public static void midorder(TreeNode t){if(t!=null){midorder(t.left);System.out.print(t.val+" ");midorder(t.right);}}public static void main(String[] args) {TreeNode t=null;t=CreatTree(t);midorder(t);TreeNode node=new TreeNode(5); t= insertNode(t,node); System.out.println(); midorder(t);}}
阅读全文
0 0
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- 在二叉查找树中插入节点
- PM&PL&SE&PG
- 吊炸天-js如何实现继承
- verilog中的一些常用操作符
- Bash脚本基础
- 谈谈"求线段交点"的几种算法(js实现,完整版)
- 在二叉查找树中插入节点
- POJ 2088 Long Night of Museums 笔记
- 原型模式--Prototype
- Read Me!
- vim中字符大小写快速转换
- RH254测试
- 关于android studio App building 加速
- Spring+SpringMVC+Mybatis(SSM)+Maven构建web项目(demo)步骤
- 机器学习中的正则化