访问我的个人博客 秋码个人博客
先定义二叉树的结构
package com.zhenqi.test;
/**
* Created by wuming on 2017/9/13.
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
public TreeNode(int x) { val = x; }
public boolean equals(Object obj) {
return super.equals(obj);
}
}
第一步在树A中查找与根结点的值一样的结点,这实际上就是树的遍历。
public boolean HasSubtreeCore(TreeNode pTreeHead1, TreeNode pTreeHead2){
boolean result = false;
if(pTreeHead1.getVal() == pTreeHead2.getVal())
result = DoesTree1HaveAllNodesOfTree2(pTreeHead1, pTreeHead2);
if(!result && pTreeHead1.getLeft() != null)
result = HasSubtreeCore(pTreeHead1.getLeft(), pTreeHead2);
if(!result && pTreeHead1.getRight() != null)
result = HasSubtreeCore(pTreeHead1.getRight(), pTreeHead2);
return result;
}
public boolean HasSubtree(TreeNode pTreeHead1, TreeNode pTreeHead2){
if((pTreeHead1 == null && pTreeHead2 != null) || (pTreeHead1 != null && pTreeHead2 == null))
return false;
if(pTreeHead1 == null && pTreeHead2 == null)
return true;
return HasSubtreeCore(pTreeHead1, pTreeHead2);
}
如果发现某一结点的值和树B的头结点的值相同,则调用DoesTree1HaveAllNodeOfTree2,做第二步判断。接下来考虑第二步,判断以树A中以N为根结点的子树是不是和树B具有相同的结构。同样,我们也可以用递归的思路来考虑:如果结点N的值和树B的根结点不相同,则以N为根结点的子树和树B肯定不具有相同的结点;如果他们的值相同,则递归地判断他们的各自的左右结点的值是不是相同。递归的终止条件是我们到达了树A或者树B的叶结点。
public boolean DoesTree1HaveAllNodesOfTree2(TreeNode pTreeHead1, TreeNode pTreeHead2){
if(pTreeHead2 == null)
return true;
if(pTreeHead1 == null)
return false;
if(pTreeHead1.getVal()!= pTreeHead2.getVal())
return false;
return DoesTree1HaveAllNodesOfTree2(pTreeHead1.getLeft(), pTreeHead2.getLeft()) &&
DoesTree1HaveAllNodesOfTree2(pTreeHead1.getRight(), pTreeHead2.getRight());
}
最后测试一下:
public static void main(String[] args){
TreeNode tree = new TreeNode(1);
tree.setLeft(new TreeNode(2));
tree.setRight(new TreeNode(3));
tree.getLeft().setLeft(new TreeNode(4));
tree.getRight().setLeft(new TreeNode(5));
tree.getRight().setRight(new TreeNode(6));
tree.getRight().getLeft().setLeft(new TreeNode(7));
tree.getRight().getLeft().setRight(new TreeNode(8));
TreeNode tree2 = new TreeNode(3);
tree2.setLeft(new TreeNode(5));
tree2.setRight(new TreeNode(6));
TreeNodeTest treeNodeTest=new TreeNodeTest();
boolean b=treeNodeTest.HasSubtree(tree,tree2);
System.out.println(b);
}