树的子结构
树的子结构
https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
有个大神的代码思路超级棒
public class Solution { public static boolean HasSubtree(TreeNode root1, TreeNode root2) { boolean result = false; //当Tree1和Tree2都不为零的时候,才进行比较。否则直接返回false if (root2 != null && root1 != null) { //如果找到了对应Tree2的根节点的点 if(root1.val == root2.val){ //以这个根节点为为起点判断是否包含Tree2 result = doesTree1HaveTree2(root1,root2); } //如果找不到,那么就再去root的左儿子当作起点,去判断时候包含Tree2 if (!result) { result = HasSubtree(root1.left,root2); } //如果还找不到,那么就再去root的右儿子当作起点,去判断时候包含Tree2 if (!result) { result = HasSubtree(root1.right,root2); } } //返回结果 return result; } public static boolean doesTree1HaveTree2(TreeNode node1, TreeNode node2) { //如果Tree2已经遍历完了都能对应的上,返回true if (node2 == null) { return true; } //如果Tree2还没有遍历完,Tree1却遍历完了。返回false if (node1 == null) { return false; } //如果其中有一个点没有对应上,返回false if (node1.val != node2.val) { return false; } //如果根节点对应的上,那么就分别去子节点里面匹配 return doesTree1HaveTree2(node1.left,node2.left) && doesTree1HaveTree2(node1.right,node2.right); }
注意这个递归部分:
result = HasSubtree(root1.left,root2);
里层的返回结果是外层的result,最里面结束层的结果是true,则会一层一层地返回true
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { bool flag=false; if(pRoot1!=NULL&&pRoot2!=NULL) { if(pRoot1->val==pRoot2->val) { flag=Judge(pRoot1,pRoot2); } if(!flag) flag=HasSubtree(pRoot1->left,pRoot2); if(!flag) flag=HasSubtree(pRoot1->right,pRoot2); } return flag; } //判断以tree1,tree2为根节点的树是否完全相等 bool Judge(TreeNode* tree1, TreeNode* tree2) { if(tree2==NULL) return true; if(tree1==NULL) return false; if(tree1->val!=tree2->val) return false; else{ return Judge(tree1->left,tree2->left)&&Judge(tree1->right,tree2->right); } } };
主要是外部函数先找到与子树根节点相同的结点,再判断以这两个根节点开始的树是否有包含关系