在二叉树中找到指定的元素,如果有重复出现的元素,要求元素为深度最深的任何一个
节点定义如下:
struct Node{
int data;
Node* left;
Node* right;
Node(int data, Node* left, Node* right)
{
this->data = data;
this->left = left;
this->right = right;
}
};
算法思想如下:
采用递归的方法,遍历每一个节点,遍历的同时,比较节点的值与要查找的值,如果相等而且该节点具有更深的深度,那么记录该节点及其深度。
C++实现如下:
#include<iostream>
using namespace std;
Node* pDeepestNode = NULL; //所寻找的最深的节点
int iDeepestDepth = 0; //该节点的深度
Node* find_deepest(
Node* pRoot, //子树的根节点
int iDepth, //子树根节点相对于总的根节点的深度
int iWanted) //要查找的值
{
if(pRoot==NULL)
return pRoot;
else if(pRoot->data==iWanted) //如果子树的根节点的值等于要寻找的值,
{
if(iDeepestDepth<iDepth) //而且子树的根节点的深度比之前找到的最深节点的深度大
{
//更新最深的节点和最深的深度
iDeepestDepth = iDepth;
pDeepestNode = pRoot;
}
}
//继续在根节点的左子树和右子树中寻找目标值
find_deepest(pRoot->left, iDepth+1, iWanted);
find_deepest(pRoot->right, iDepth+1, iWanted);
}
Node* createTree()
{
Node* n9 = new Node(5,NULL,NULL);
Node* n8 = new Node(11,NULL,NULL);
Node* n7 = new Node(4,NULL,NULL);
Node* n6 = new Node(2,NULL,NULL);
Node* n5 = new Node(6,n9,n8);
Node* n4 = new Node(9,n7,NULL);
Node* n3 = new Node(7,n6,n5);
Node* n2 = new Node(5,NULL,n4);
Node* n1 = new Node(2,n3,n2);
return n1;
}
int main(){
Node* n = createTree();
find_deepest(n,1,5);
//如果iDeepestDepth等于0,说明在树中没有找到指定值
cout<<iDeepestDepth<<endl;
return 0;
}
![](https://img-my.csdn.net/uploads/201208/23/1345672070_2758.png)
对于如上所示的树,程序输出节点值为5的节点的最大深度是4.