淘客自己的网站怎么做,网站建设 事项,正在备案怎么建网站,网站代备572. 另一棵树的子树
解题思路
遍历二叉树的思路针对每一个节点判断该节点的子树和subtree是不是相等需要编写判断两个子树是否相等的函数 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* …572. 另一棵树的子树
解题思路
遍历二叉树的思路针对每一个节点判断该节点的子树和subtree是不是相等需要编写判断两个子树是否相等的函数
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val val;* this.left left;* this.right right;* }* }*/
class Solution {// 比较两个树是不是相等public boolean isSame(TreeNode root,TreeNode root1){// 二叉树的遍历问题 针对当前节点 写出所有递归出口if(root null root1 null){return true;}if(root null || root1 null){return false;}if(root.val ! root1.val){return false;}return isSame(root.left,root1.left) isSame(root.right,root1.right);}public boolean isSubtree(TreeNode root, TreeNode subRoot) {// 二叉树的遍历问题 针对二叉树每一个点继续遍历 模板题// 对于遍历到的每一个节点 也就是先写出递归出口if(root null){return subRoot null;}if(isSame(root,subRoot)){return true;}// 从左右子树开始继续寻找是否有相同的子树return isSubtree(root.left,subRoot) || isSubtree(root.right,subRoot);}
}