Enter two binary trees, a, B, to determine whether a is a sub-structure of a. (PS: We agree that an empty tree is not a sub-structure of any tree)
1 /**2 Public class TreeNode {3 int val = 0;4 TreeNode left = null;5 TreeNode right = null;6 7 Public TreeNode (int val) {8 this.val = val;9 Ten } One A } - */ - Public classSolution { the Public BooleanHassubtree (TreeNode root1,treenode root2) { - - Booleanresult =false; - + if(Root1! =NULL&& Root2! =NULL){ - + if(Root1.val = =root2.val) { Aresult =doestree1hastree2 (ROOT1,ROOT2); at } - - //recursively traverse the left subtree - if(!result) { -result =Hassubtree (Root1.left, root2); - } in - //recursive traversal of right sub-tree to if(!result) { +result =Hassubtree (Root1.right, root2); - } the } * $ returnresult;Panax Notoginseng - } the + A Public Booleandoestree1hastree2 (TreeNode root1,treenode root2) { the + if(Root2 = =NULL){ - return true; $ } $ - if(ROOT1 = =NULL){ - return false; the } - Wuyi if(Root1.val! =root2.val) { the return false; - } Wu - returnDoestree1hastree2 (Root1.left, Root2.left) &&doestree1hastree2 (Root1.right, root2.right); About } $}
Sub-structure of the binary tree tree