面試題26:樹的子結構
阿新 • • 發佈:2020-07-25
考察二叉樹的遍歷。
C++版
#include <iostream> #include <algorithm> using namespace std; // 定義二叉樹 struct TreeNode{ int val; struct TreeNode* left; struct TreeNode* right; TreeNode(int val):val(val),left(nullptr),right(nullptr){} }; bool doesTree1HaveTree2(TreeNode* pRoot1, TreeNode* pRoot2){ if(pRoot2 == nullptr) return true; if(pRoot1 == nullptr) return false; if(pRoot1->val != pRoot2->val) return false; return doesTree1HaveTree2(pRoot1->left, pRoot2->left) && doesTree1HaveTree2(pRoot1->right, pRoot2->right); } bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2){ bool result = false; if(pRoot1 != nullptr && pRoot2 != nullptr){ if(pRoot1->val == pRoot2->val) result = doesTree1HaveTree2(pRoot1, pRoot2); // 如果沒找到,則往左找 if(!result) result = HasSubtree(pRoot1->left, pRoot2); // 如果還沒找到,則往右找 if(!result) result = HasSubtree(pRoot1->right, pRoot2); } return result; } int main() { char *p = "hello"; // p[0] = 'H'; cout<<p<<endl; return 0; }