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; }};
阅读全文
0 0
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- 572. Subtree of Another Tree
- Subtree of Another Tree
- Subtree of Another Tree
- 572. Subtree of Another Tree Medium
- 572. Subtree of Another Tree(Easy)
- [LeetCode]572. Subtree of Another Tree
- [leetcode]: 572. Subtree of Another Tree
- 控件 TextView、EditText
- 手工自动重跑kettle报错Job
- Http接口的分类
- git一键部署代码到远程服务器
- netty入门学习(4)-LengthFieldPrepender和LengthFieldBasedFrameDecoder
- 572. Subtree of Another Tree
- 兔子产子
- 6月3日,每日20行。
- 《飞屋环游记》让心去旅行
- Java数组
- 判断一个数组序列为二叉树的后序遍历序列
- poj 1852
- 逆波兰表达式的产生及计算
- 安卓入门之"搭建Android的开发环境"