二叉查詢樹(binary search tree),也稱有序二叉樹(ordered binary tree),排序二叉樹(sorted binary tree),是指一棵空樹或者具有下列性質的二叉樹:
1. 若任意節點的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
2. 若任意節點的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
3. 任意節點的左、右子樹也分別為二叉查詢樹;
4. 沒有鍵值相等的節點;
本文跟前文一樣只是實現了增加和查詢功能,需要乙個節點輔助類:
@inte***ce binarynode:nsobject
@property (strong,nonatomic) nsstring *key;//鍵
@property (strong,nonatomic) nsstring *value;//值
@property (strong,nonatomic) binarynode *left;//左子樹的節點
@property (strong,nonatomic) binarynode *right;//右子樹的節點
@property (assign,nonatomic) nsinteger childcount;//以該結點為根的自述中的結點總數
-(void)initwithdata:(nsstring *)key value:(nsstring *)value childcount:(nsinteger)childcount;
@end
binarynode實現**:
@implementation binarynode
-(void)initwithdata:(nsstring *)key value:(nsstring *)value childcount:(nsinteger)childcount
@end
二叉查詢樹需要定義乙個根結點:
@inte***ce binarysearchtree : nsobject
@property (strong,nonatomic) binarynode *root;//二叉平衡樹的根節點
-(nsstring *)get:(nsstring *)key;//獲取鍵對應的值
-(void)put:(nsstring *)key value:(nsstring *)value;//插入鍵值對
@end
實現**:
@implementation binarysearchtree
-(nsstring *)get:(nsstring *)key
-(nsstring *)getbykey:(binarynode *)node key:(nsstring *)key
//左右節點進行比較,每個結點的鍵值大於左子樹的結點值小於右子樹的結點值
nsinteger compare=[key integervalue]-[node.key integervalue];
if (compare>0) else if(compare<0)else
}//-(void)put:(nsstring *)key value:(nsstring *)value
-(binarynode *)putnode:(binarynode *)node key:(nsstring *)key value:(nsstring *)value
nsinteger compare=[key integervalue]-[node.key integervalue];
if (compare>0) else if(compare<0)else
node.childcount=[self childsizecount:node.left]+[self childsizecount:node.right]+1;
return node;
}-(nsinteger)childsize
-(nsinteger)childsizecount:(binarynode *)nodeelse
}@end
測試:
binarysearchtree *binarytree=[[binarysearchtree alloc]init];
[binarytree put:@"3" value:@"flyelephant"];
[binarytree put:@"9" value:@""];
[binarytree put:@"10" value:@""];
[binarytree put:@"0" value:@"228407086"];
nsstring *temp=[binarytree get:@"9"];
nslog(@"二叉查詢樹:%@",temp);
效果如下: 二叉查詢樹演算法
判斷二插查詢樹是否含有 指定結點 param x return public boolean contains t x private boolean contains t x binarynode t int compareresult x.compareto t.element if compa...
演算法導論 二叉查詢樹
部分實現,用insert生成二叉查詢樹。暫無delete函式。建立查詢樹是用insert逐個插入。比較簡陋,希望有所幫助。includeusing namespace std struct node class searchtree void create void insert node newn...
二叉樹查詢演算法
定義樹節點 class treenode def init self,x self.val x self.left none self.right none先序遍歷,遞迴 def preorder root treenode 遞迴地,先序遍歷二叉樹 if root none return else ...