判斷一個節點是否在二叉樹中,判斷tree2是否為tree1的子樹
阿新 • • 發佈:2019-01-03
1、判斷一個節點是否在一棵二叉樹中。
先判斷根節點,遞迴判斷左子樹,遞迴判斷右子樹。
2、判斷一顆二叉樹是是否是另一顆樹的子樹。比如tree2是tree1的子樹。
先判斷根,根相同再判斷左右子樹如果所有的都相同,則此樹是另一個樹的子樹。 如果只有根相同,則向下繼續找和跟相同的結點。
程式碼:
#include<iostream>
using namespace std;
struct Node
{
int _data;
Node* _leftchild;
Node* _rightchild;
Node(int x)
:_data(x)
, _leftchild(NULL)
, _rightchild(NULL)
{}
};
class BinaryTree
{
public:
BinaryTree(const int a[], int size, int invalide)
{
int index = 0;
_root = _CreateBinaryTree(a, size, index, invalide);
}
Node* _CreateBinaryTree(const int a[], int size, int &index, int invalide)
{
Node* root = NULL;
if (index < size && a[index] != invalide)
{
root = new Node(a[index]);
root->_leftchild = _CreateBinaryTree(a, size, ++index, invalide);
root->_rightchild = _CreateBinaryTree(a, size, ++index, invalide);
}
return root;
}
//判斷一個節點是否在一棵二叉樹中。(注意多測幾個節點,看是否都能找到)
bool IsInTree(Node* node)
{
return _IsInTree(_root, node);
}
bool _IsInTree(Node* root, Node* node)
{
if (root == NULL)
return false;
if (root == node)
return true;
if (_IsInTree(root->_leftchild, node) || _IsInTree(root->_rightchild, node))
return true;
return false;
}
//判斷一顆二叉樹是是否是另一顆樹的子樹。比如tree2是tree1的子樹。
bool IsChildTree(Node* pRoot)
{
return _IsChildTree(_root, pRoot);
}
bool __IsChildTree(Node* root, Node* pRoot)
{
if (root == NULL)
return false;
if (pRoot == NULL)
return true;
if (root->_data != pRoot->_data)
return false;
return __IsChildTree(root->_leftchild, pRoot) && __IsChildTree(root->_rightchild, pRoot->_rightchild);
}
bool _IsChildTree(Node* root, Node* pRoot)
{
bool ret = false;
if (root != NULL&&pRoot != NULL)
{
if (root->_data == pRoot->_data)
ret = __IsChildTree(root, pRoot);
if (!ret)
ret = _IsChildTree(root->_leftchild, pRoot);
if (!ret)
ret = _IsChildTree(root->_rightchild, pRoot);
}
return ret;
}
private:
Node* _root;
};
int main()
{
system("pause");
return 0;
}