标签:实现 tree sub 节点 ++ off item c++ scribe
验证B是不是A的子树,直觉做法,按照任意次序遍历A树,一旦出现和B树根节点相同的子节点,就将以此节点为根的子树与B树相比较,满足则查找成功,否则查找失败。树的先序遍历最为直观,此处以先序遍历为例,给出C++实现代码:
/* 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 isSub=false; //出现两树中有任意一个为空,则返回false if(pRoot1!=NULL && pRoot2!=NULL){ if(pRoot1->val==pRoot2->val){ isSub=doesTree1HaveTree2(pRoot1,pRoot2); }if(!isSub){ isSub=HasSubtree(pRoot1->left,pRoot2); }if(!isSub){ isSub=HasSubtree(pRoot1->right,pRoot2); } } return isSub; } bool doesTree1HaveTree2(TreeNode* pRoot1, TreeNode* pRoot2){ if(pRoot2==NULL){ return true; } if(pRoot1==NULL){ return false; } if(pRoot1->val!=pRoot2->val){ return false; } return doesTree1HaveTree2(pRoot1->left,pRoot2->left) && doesTree1HaveTree2(pRoot1->right,pRoot2->right); } };
标签:实现 tree sub 节点 ++ off item c++ scribe
原文地址:https://www.cnblogs.com/fancy-li/p/11616199.html