面试题:判断一个节点是否在一棵二叉树中

来源:互联网 发布:2017java不好找工作了 编辑:程序博客网 时间:2024/06/09 23:59

题目:判断一个节点是否在一棵二叉树中
结点定义如下

struct BinaryTree{    BinaryTree(char data)    :_pLeft(NULL)    , _pRight(NULL)    , _data(data)    {}    BinaryTree *_pLeft;    BinaryTree *_pRight;    char _data;};

首先附上创建树代码

void CreateBinaryTree(BinaryTree *&pRoot, char *str,size_t size, size_t &index){    if (index < size && str[index] != '#')    {        pRoot = new BinaryTree(str[index]);        CreateBinaryTree(pRoot->_pLeft, str, size, ++index);        CreateBinaryTree(pRoot->_pRight, str, size, ++index);    }}

思路:判断当前结点与查找的结点是否相等,如果不相等寻找左子树,继而寻找右子树,这样用递归很容易实现

  • 代码实现
bool IsNodeInTree(BinaryTree *pRoot,BinaryTree *pNode){    if (NULL == pRoot || NULL == pNode)        return false;    if (pRoot->_data == pNode->_data)        return true;    if (IsNodeInTree(pRoot->_pLeft, pNode) || IsNodeInTree(pRoot->_pRight, pNode))        return true;        return false;}
  • 测试用例
void funtest(){     BinaryTree *pRoot;    char *str = "abdh###e##cf##g#i";    size_t index = 0;    CreateBinaryTree(pRoot, str, strlen(str), index);    BinaryTree *node = pRoot->_pLeft;    cout << node->_data << " ";    bool ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = pRoot->_pLeft->_pLeft;    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = pRoot->_pLeft->_pLeft;    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = pRoot->_pLeft->_pRight;    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = pRoot->_pRight;    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = pRoot->_pRight->_pLeft;    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = pRoot->_pRight->_pRight;    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = pRoot->_pRight->_pRight->_pRight;    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = new BinaryTree('n');    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    node = new BinaryTree('e');    cout << node->_data << " ";    ret = IsNodeInTree(pRoot, node);    cout << ret << endl;    ret = IsNodeInTree(pRoot, NULL);    cout << ret << endl;}
阅读全文
0 0
原创粉丝点击