考察点
树的遍历,递归思想
知识点
题目
分析
本题目要求判断树B是否是另外一颗树A的子结构,按照正常的递归思维就可以解决这道题目。首先要求这俩颗树的根结点必须一样,所以如果树A的根结点和树B的根结点不一样了则需要递归树A去找到和树B根结点一样的子树,找到以后再去递归判断这俩个树的左子树和右子树是否完全一致
public class Eighteen {public static void main(String args[]) {BinaryTree binaryTree = new BinaryTree();binaryTree.insertTree(8);binaryTree.insertTree(7);binaryTree.insertTree(9);binaryTree.insertTree(5);binaryTree.insertTree(6);binaryTree.insertTree(2);BinaryTree binaryTreeSub = new BinaryTree();binaryTreeSub.insertTree(7);binaryTreeSub.insertTree(5);binaryTreeSub.insertTree(6);System.out.println(isSubStruct(binaryTree.getRoot(),binaryTreeSub.getRoot()));BinaryTree binaryTreeSubOne = new BinaryTree();binaryTreeSubOne.insertTree(7);binaryTreeSubOne.insertTree(5);binaryTreeSubOne.insertTree(6);binaryTreeSubOne.insertTree(11);System.out.println(isSubStruct(binaryTree.getRoot(),binaryTreeSubOne.getRoot()));BinaryTree binaryTreeSubTwo = new BinaryTree();System.out.println(isSubStruct(binaryTree.getRoot(),binaryTreeSubTwo.getRoot()));}public static boolean isSubStruct(Node treeOne,Node treeTwo) {boolean result = false;if (treeOne != null && treeTwo != null) {if (treeOne.val == treeTwo.val) {result = isSubDeepResult(treeOne,treeTwo);}if (!result) {result = isSubStruct(treeOne.leftChild,treeTwo);}if (!result) {result = isSubStruct(treeOne.rightChild,treeTwo);}}return result;}public static boolean isSubDeepResult(Node treeOne,Node treeTwo) {//如果树B为空了代表树B已经遍历完了,说明结构一样if (treeTwo == null) {return true;}//到这一步表面,树B还没有遍历完树A确遍历完了说明俩个树结构已经不一样了if (treeOne == null) {return false;}if (treeOne.val != treeTwo.val) {return false;}return isSubDeepResult(treeOne.leftChild,treeTwo.leftChild) && isSubDeepResult(treeOne.rightChild,treeTwo.rightChild);}
}
public class Node{int val;Node leftChild;Node rightChild;public Node(int data) {this.val = data;this.leftChild = null;this.rightChild = null;}
}
public class BinaryTree {Node root;public BinaryTree() {this.root = null;}public void insertTree(int val) {if (this.root == null) {Node root = new Node(val);this.root = root;} else {insertChildTree(this.root,val);}}public void insertChildTree(Node node,int val) {if (node != null && val <= node.val) {if (node.leftChild == null) {node.leftChild = new Node(val);} else {insertChildTree(node.leftChild,val);}}if (node != null && val > node.val) {if (node.rightChild == null) {node.rightChild = new Node(val);} else {insertChildTree(node.rightChild,val);}}}public Node getRoot() {return this.root;}public void prePrint(Node node) {if (node == null) {return;}System.out.print(node.val + " ");prePrint(node.leftChild);prePrint(node.rightChild);}
}