572. Subtree of Another Tree

来源:互联网 发布:只有我知 杭州见面会 编辑:程序博客网 时间:2024/05/17 07:42

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.
这道题就是递归的方法去算,不断抓住一个节点,然后去比较每个节点的左右子树的数值包括他们是否为空。

代码如下:

/** * 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 isSametree(TreeNode* s, TreeNode* t){        if(s==NULL&&t==NULL)return true;        if(s==NULL&&t!=NULL||s!=NULL&&t==NULL||s->val!=t->val){            return false;        }        bool left=isSametree(s->left,t->left);        bool right=isSametree(s->right,t->right);        return (left&&right);    }    bool isSubtree(TreeNode* s, TreeNode* t) {        bool res=false;        if(s!=NULL&&t!=NULL){            if(t->val==s->val){                res=isSametree(s,t);            }            if(!res)res=isSubtree(s->left,t);            if(!res)res=isSubtree(s->right,t);        }        return res;    }};
原创粉丝点击