剑指OFFER----面试题26. 树的子结构

链接:https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/

 

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isPart(TreeNode* A, TreeNode* B) {
        if (A == NULL || B == NULL) {
            return B == NULL ? true : false;
        }
        if (A->val != B->val) {
            return false;
        }
        return isPart(A->left, B->left) && isPart(A->right, B->right);
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if (A == NULL || B == NULL) {
            return false;
        }
        return isPart(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B);
    }
};

 

posted @ 2020-02-25 19:38  景云ⁿ  阅读(169)  评论(0编辑  收藏  举报