面试题26:树的子结构

考察二叉树的遍历。

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;
}
posted @ 2020-07-25 20:22  程序员曾奈斯  阅读(141)  评论(0编辑  收藏  举报