⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 wex11_26.cpp

📁 数据结构C++代码,经典代码,受益多多,希望大家多多支持
💻 CPP
字号:
#include <iostream.h>
#pragma hdrstop

#include "treelib.h"
#include "treeprnt.h"
#include "bstree.h"

// determine the depth of elem in tree t. return
// -1 if elem is not in the tree
template <class T>
int NodeLevel(BinSTree<T>& tree, const T& elem)
{  
	// obtain a pointer to the root node of tree
	TreeNode<T> *t = tree.GetRoot();
	// initially, depth = -1
	int d = -1;
   
	// move through the tree until elem found or
	// a NULL pointer is found
	while(t != NULL)
	{
		// moving up one level
		d++;
		// if data in current node matches elem,
		// return depth d
		if (t->data == elem)
			return d;
		else
		// move left if elem < t->data
		if (elem < t->data)
			t = t->Left();
		else
			// move right if elem >= t->data
			t = t->Right();
	}
	
	// return the depth of elem in the tree
	return d;
}

void main(void)
{
	// create a binary search tree built from the data
	// in array a
    BinSTree<int> tree;
    int a[] = {50,35,75,15,28,85,35,19,95,44,55,33,12,5,3};
    
    // create tree and print it
    for(int i=0;i < 15;i++)
    	tree.Insert(a[i]);
    PrintVTree (tree.GetRoot(), 2,65);
    cout << endl << endl << endl;
    
	// find and print the depth of the nodes having
	// data values 19 and 85
    cout << "Depth of 19: " << NodeLevel(tree,19) << endl;
    cout << "Depth of 85: " << NodeLevel(tree,85) << endl;
    
}

/*
<Run>

                              50

              35                              75

      15              35              55              85

  12      28              44                              95

 5      19  33

 3


Depth of 19: 4
Depth of 85: 2
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -