LeetCode572. Subtree of Another Tree

版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/87992657

572. Subtree of Another Tree

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.

Example 1:

Given tree s:
     3
    / \
   4   5
  / \
 1   2
Given tree t:
   4
  / \
 1   2
Return true, because t has the same structure and node values with a subtree of s.

Example 2:

Given tree s:
     3
    / \
   4   5
  / \
 1   2
    /
   0
Given tree t:
   4
  / \
 1   2
Return false.

题目:判断树t是不是数s的子树。

思路:参见tree traversal.

For each node during pre-order traversal of s, use a recursive function isSame to validate if sub-tree started with this node is the same with t.

对树s进行前序遍历,获得对应根节点,判断s每个根节点下对应的子树是不是和t相等(isSame),如果s中所有根节点下对应的子树都不和t相等,返回false

工程代码下载

/**
 * 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 isSubtree(TreeNode* s, TreeNode* t) {
        if(s == nullptr)
            return false;
        if(isSame(s, t))
            return true;
        return isSubtree(s->left, t) || isSubtree(s->right, t);
    }
private:
    bool isSame(TreeNode* p1, TreeNode* p2){
        if(p1 == nullptr && p2 == nullptr)
            return true;
        if(p1 == nullptr || p2 == nullptr)
            return false;
        if(p1->val != p2->val)
            return false;
        return isSame(p1->left, p2->left) && isSame(p1->right, p2->right);
    }
};

猜你喜欢

转载自blog.csdn.net/grllery/article/details/87992657