本文主要是介绍is subtree or not,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
判断一个树是不是另一个树的子树
boolean issametree(TreeNode root1, TreeNode root2) {if (root1 == null && root2 == null)return true;if (root1 != null && root2 != null) {return root1.val == root2.val && issametree(root1.left, root2.left)&& issametree(root1.right, root2.right);}return false;}public boolean issubtree(TreeNode big, TreeNode small) {if (big != null && small != null) {if (big.val == small.val) {if (issametree(big, small))return true;}else {if (big.left != null && issubtree(big.left, small)) {return true;}if (big.right != null && issubtree(big.right, small)) {return true;}}}return false;}public static void main(String[] args) {SameTreeSubTree s = new SameTreeSubTree();TreeNode tn1 = new TreeNode(1);TreeNode tn2 = new TreeNode(2);TreeNode tn3 = new TreeNode(3);TreeNode tn4 = new TreeNode(4);TreeNode tn5 = new TreeNode(5);tn1.left = tn2;tn1.right = tn3;tn4.left = tn5;System.out.println(s.issubtree(tn1, tn2));System.out.println(s.issubtree(tn1, tn4));}
这篇关于is subtree or not的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!