第十章(二叉树)

二叉树的节点信息包括:左指针,右指针,数据。二叉树首先定义根节点为null;插入节点是很重要的部分。

			function Node(data,left,right){
				this.data=data;
				this.right=left;
				this.left=right;
				this.show=show;
			}
			function show(){
				return this.data;
			}
			function BST(){
				this.root=null;
				this.insert=insert;
				this.inOrder=inOrder;//中序
				this.preOrder=preOrder;//先序
				this.postOrder=postOrder;//后序
				this.size=size;//返回节点个数
				this.find=find;//查找某个值是否在二叉树中
				this.getMin=getMin;//查找该书中最小的值
				this.getMax=getMax;//查找该树中最小的值
			}
			function size(node){
				if(node==null) return 0;
				return size(node.left)+size(node.right)+1;
			}
			function insert(data){
				var n=new Node(data,null,null);
				if(this.root==null){
					this.root=n;
				}
				else{
					var current=this.root;
					var parent;
					while (true){
						parent=current;
						if(data<current.data){
							current=current.left;
							if(current==null){
								parent.left=n;
								break;
							}
						}
						else{
							current=current.right;
							if(current==null){
								parent.right=n;
								break;
							}
						}
					}
				}
			}
			function inOrder(node){
				if(!(node==null)){
					inOrder(node.left);
					console.log(node.data);
					inOrder(node.right);
				}
			}
			function preOrder(node){
				if(!(node==null)){
					console.log(node.data+" ");
					preOrder(node.left);
					preOrder(node.right);
				}
			}
			function postOrder(node){
				if(!(node==null)){
					postOrder(node.left);
					postOrder(node.right);
					console.log(node.data);
				}
			}
			
			//查找最小值
			function getMin(){
				var current=this.root;
				while(!(current.left==null)){
					current=current.left;
				}
				return current.data;
			}
			//查找最大值
			function getMax(){
				var current=this.root;
				while(current.right!=null){
					current=current.right;
				}
				return current.right;
			}
			//查找固定的值
			function find(data){
				var current=this.root;
				while (current!=null){
					if(current.data==data){
						return current;
					}
					else if(data<current.data){
						current = current.left;
					}
					else{
						current=current.right;
					}
				}
				return null;
			}
			//主程序
			var nums=new BST();
			nums.insert(323);
			nums.insert(123);
			nums.insert(152);
			nums.insert(23);
			nums.insert(98);
			nums.insert(56);
			nums.insert(8);
			nums.insert(93);
			
			console.log("中序:");
			inOrder(nums.root);
			console.log("先序:");
			preOrder(nums.root);
			console.log("后序:");
			postOrder(nums.root);
			if(nums.find(123)!=null){
				console.log("found "+123);
			}
			else{
				onsole.log("can't not found "+123);
			}
			console.log("该树节点的个数是:"+nums.size(nums.root));


猜你喜欢

转载自blog.csdn.net/prince_fmx/article/details/78177578
今日推荐