您的位置:首页 > 理论基础 > 数据结构算法

数据结构——确定一个二叉树是不是另一个二叉树的子树

2016-12-04 14:17 423 查看
原文地址:Check if a binary tree is subtree of another binary tree | Set 1

已知两个二叉树,看一下第一个树是不是第二个树的子树。一个树T的子树是树S,这个树由是T中的一个节点及其它的下属节点组成的。子树对应的是根节点的话,那就是整个树;子树对应的是任意其他节点的话叫做正常子树(proper subtree)。

例如,在下面的例子中,树S是树T的一个子树。

Tree 2
10
/    \
4       6
\
30


Tree 1
26
/   \
10     3
/    \     \
4       6      3
\
30


解决方案:先序遍历树T。对于每一个遍历过的节点,查看这个节点是否等于S的根节点。

// Java program to check if binary tree is subtree of another binary tree

// A binary tree node
class Node
{
int data;
Node left, right, nextRight;

Node(int item)
{
data = item;
left = right = nextRight = null;
}
}

class BinaryTree
{
Node root1,root2;

/* A utility function to check whether trees with roots as root1 and
root2 are identical or not */
boolean areIdentical(Node root1, Node root2)
{

/* base cases */
if (root1 == null && root2 == null)
return true;

if (root1 == null || root2 == null)
return false;

/* Check if the data of both roots is same and data of left and right
subtrees are also same */
return (root1.data == root2.data
&& areIdentical(root1.left, root2.left)
&& areIdentical(root1.right, root2.right));
}

/* This function returns true if S is a subtree of T, otherwise false */
boolean isSubtree(Node T, Node S)
{
/* base cases */
if (S == null)
return true;

if (T == null)
return false;

/* Check the tree with root as current node */
if (areIdentical(T, S))
return true;

/* If the tree with root as current node doesn't match then
try left and right subtrees one by one */
return isSubtree(T.left, S)
|| isSubtree(T.right, S);
}

public static void main(String args[])
{
BinaryTree tree = new BinaryTree();

// TREE 1
/* Construct the following tree
26
/   \
10     3
/    \     \
4      6      3
\
30  */

tree.root1 = new Node(26);
tree.root1.right = new Node(3);
tree.root1.right.right = new Node(3);
tree.root1.left = new Node(10);
tree.root1.left.left = new Node(4);
tree.root1.left.left.right = new Node(30);
tree.root1.left.right = new Node(6);

// TREE 2
/* Construct the following tree
10
/    \
4      6
\
30  */

tree.root2 = new Node(10);
tree.root2.right = new Node(6);
tree.root2.left = new Node(4);
tree.root2.left.right = new Node(30);

if (tree.isSubtree(tree.root1, tree.root2))
System.out.println("Tree 2 is subtree of Tree 1");
else
System.out.println("Tree 2 is not a subtree of Tree 1");
}
}

// This code has been contributed by Mayank Jaiswal


输出:

Tree 2 is subtree of Tree 1


时间复杂度:最坏情况下上述解法的时间复杂度是O(mn),在这里m与n分别是已知两个树中的节点数目。

我们可以在O(n)的时间内解决问题,请参考Check if a binary tree is subtree of another binary tree | Set 2O(n) 的解决方案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 二叉树
相关文章推荐