二叉查詢樹

2021-06-18 23:46:41 字數 2746 閱讀 6066

二叉查詢樹或者是一棵空樹;或者是具有下列性質的二叉樹:

(1)若左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;

(2)若右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; (

3)左、右子樹也分別為二叉排序樹

#include #include typedef struct treenode

bsearchtreenode;

int insertnode(bsearchtreenode **proot, int num)

if (num < (*proot)->m_nvalue)

else

insertnode(&(*proot)->m_pleft, num);

} else if (num > (*proot)->m_nvalue)

else

insertnode(&(*proot)->m_pright, num);

} else }

bsearchtreenode* search(bsearchtreenode *proot, int num)

bsearchtreenode* searchmin(bsearchtreenode *proot)

bsearchtreenode* searchmax(bsearchtreenode *proot)

bsearchtreenode* searchpredecessor(bsearchtreenode *pnode)

if (plocal->m_pparent == null)

return null;

else

return plocal->m_pparent; }}

bsearchtreenode* searchsuccessor(bsearchtreenode *pnode)

if (plocal->m_pparent == null)

return null;

else

return plocal->m_pparent; }}

int removenode(bsearchtreenode **proot, int num)

else

else if (ptoberemoved->m_pparent->m_pright == ptoberemoved)

}} else if (ptoberemoved->m_pleft && ptoberemoved->m_pright == null)

else if (ptoberemoved->m_pleft == null && ptoberemoved->m_pright)

else

return 1; }

void preordervisit(bsearchtreenode *proot)

}void postordervisit(bsearchtreenode *proot)

else

}}void inordervisit(bsearchtreenode *proot)

ptemp= nodes.top();

nodes.pop();

printf("%d ", ptemp->m_nvalue);

if (ptemp->m_pright != null)

}}void inorder_visit(bsearchtreenode *proot)

printf("%d ", ptemp->m_nvalue);

-- top;

if (ptemp->m_pright)

}}int main()

; int length = sizeof(key) / sizeof(int);

int i;

for (i = 0; i < length; i++)

preordervisit(ptree);

printf("\n");

inordervisit(ptree);

printf("\n");

postordervisit(ptree);

printf("\n");

bsearchtreenode *min = searchmin(ptree);

bsearchtreenode *max = searchmax(ptree);

printf("min is:%d\n", min->m_nvalue);

printf("max is:%d\n", max->m_nvalue);

if (searchpredecessor(min) == null)

printf("no node smaller than %d\n", min->m_nvalue);

if (searchsuccessor(max) == null)

printf("no node larger than %d\n", max->m_nvalue);

int tobefind = 10;

bsearchtreenode *p = search(ptree, tobefind);

if (p)

else

printf("%d do not exit in the tree\n", tobefind);

int toberemoved = 9;

if (removenode(&ptree, toberemoved))

else

printf("fail to remove %d\n", toberemoved);

return 1;

}

二叉樹 二叉查詢樹

構建二叉樹,判斷是否為二叉查詢樹,遞迴先序遍歷,非遞迴中序遍歷 include include include include using namespace std 二叉樹結點 struct treenode 鍊錶結點 struct listnode struct tempnodetempnode...

二叉樹 二叉查詢樹

二叉樹 binary tree 一種樹型結構,每個節點最多擁有兩個節點。如下圖 幾種型別的二叉樹 1.full binary tree 每個節點的孩子數 是 0 或者 2.對高度沒有要求。如下圖 2.perfect binary tree 這個就是最完美的樹,顧名思義,所有葉子節點都有相同的深度,並...

樹(樹,二叉樹,二叉查詢樹)

1.定義 n n 0 個結點構成的有限集合。當n 0時,稱為空樹 2.對於任一棵非空樹 n 0 它具備以下性質 1 樹中有乙個稱為 根 root 的特殊結點,用 r 表示 2 其餘結點可分為m m 0 個互不相交的有限集t1,t2,其中每個集合本身又是一棵樹,稱為原來樹的子樹。3.樹的一些性質 1 ...