leetcode 572. Subtree of Another Tree 子树判断 + 深度优先遍历DFS
2017-12-20 09:15
597 查看
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:
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:
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
本题题意很简单,直接递归遍历即可
代码如下:
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.
本题题意很简单,直接递归遍历即可
代码如下:
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <numeric> #include <cmath> using namespace std; /* 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 == NULL) return false; else if (isSame(s, t) == true) return true; else return isSubtree(s->left, t) || isSubtree(s->right, t); } bool isSame(TreeNode* s, TreeNode* t) { if (s == NULL && t == NULL) return true; else if (s == NULL && t != NULL || s != NULL && t == NULL) return false; else { if (s->val != t->val) return false; else return isSame(s->left,t->left) && isSame(s->right,t->right); } } };
相关文章推荐
- leetcode 110. Balanced Binary Tree(平衡二叉树的判断) DFS深度优先遍历
- leetcode 100. Same Tree 二叉树DFS深度优先遍历
- leetcode 236. Lowest Common Ancestor of a Binary Tree 最近公告祖先LCA + 二叉树 + 深度优先遍历DFS
- leetcode 671. Second Minimum Node In a Binary Tree 第二小数字 + 深度优先遍历DFS
- leetcode 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化 + 深度优先遍历DFS
- leetcode 508. Most Frequent Subtree Sum 子树和 + 一个简单的DFS深度优先遍历的做法
- leetcode 684. Redundant Connection 邻接表的环的判断 + 深度优先遍历DFS
- leetcode 662. Maximum Width of Binary Tree 二叉树最大宽度 + 深度优先遍历DFS
- leetcode 543. Diameter of Binary Tree 最长树的片段 + 深度优先遍历DFS
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- leetcode 257. Binary Tree Paths 深度优先遍历DFS
- leetcode 113. Path Sum II DFS深度优先遍历
- leetcode 653. Two Sum IV - Input is a BST 中序遍历 + 深度优先遍历DFS
- leetcode 343. Integer Break 深度优先遍历DFS(超时) + 最大子元素乘积 + 发现规律
- leetcode 377. Combination Sum IV 组合之和 + DP动态规划 + DFS深度优先遍历
- leetcode 394. Decode String 字符串解码 + DFS深度优先遍历求解
- leetcode 144. Binary Tree Preorder Traversal 二叉树前序遍历 + 深度优先遍历DFS
- leetcode 606. Construct String from Binary Tree 前序遍历 + 深度优先遍历DFS
- leetcode 417. Pacific Atlantic Water Flow可以到达两边的点+经典DFS深度优先遍历做法
- leetcode 22. Generate Parentheses DFS深度优先遍历