[Leetcode] 572. Subtree of Another Tree 解题报告

来源:互联网 发布:ubuntu搭建网络电话 编辑:程序博客网 时间:2024/06/01 08:33

题目

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.

思路

练手题目,哈哈。

代码

/** * 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) {        vector<TreeNode*> nodes;        preorder(s, nodes);        for (auto n : nodes) {            if (sameTree(t, n)) {                return true;            }        }        return false;    }private:    void preorder(TreeNode *s, vector<TreeNode*> &nodes) {        if (s == NULL) {            return;        }        nodes.push_back(s);        preorder(s->left, nodes);        preorder(s->right, nodes);    }    bool sameTree(TreeNode *t1, TreeNode *t2) {        if (t1 == NULL && t2 == NULL) {            return true;        }        else if (t1 == NULL || t2 == NULL) {            return false;        }        else {            if (t1->val != t2->val) {                return false;            }            else {                return sameTree(t1->left, t2->left) && sameTree(t1->right, t2->right);            }        }    }};

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 青花瓷签字笔价格 青花瓷康熙 元青花瓷器市场价格 青花瓷鱼尾裙 青花瓷装饰 康熙青花玲珑瓷 清都山水郎 清芷园二手房 清芷园 北京清芷园房价 保定市清苑区 清苑县房价 清苑中学吧 清苔学院 清炒菜苔的做法 金苔鼠和清道夫哪个好 空怀若谷 皆若空游无所依 合肥金荷苑 兰蔻清莹嫩肤水 清莹保湿洁面乳 清凌凌水蓝莹莹天原唱 兰蔻清莹洁面乳 兰蔻清莹洁面卸妆乳 sk2清莹露怎么用 skii清莹露 skii清莹露怎么用 清莹露怎么用 sk2嫩肤清莹露怎么用 skii环采臻皙清莹露 火腿娃娃菜汤 素菜汤 娃娃菜汤 俄式红菜汤 波菜汤怎么做好吃 菜汤怎么做 菜汤做法 卤菜汤料的制作方法 家常素菜汤100道 陈肾西洋菜汤 粉丝娃娃菜汤的做法