572. Subtree of Another Tree
来源:互联网 发布:游戏租号 软件 编辑:程序博客网 时间:2024/06/06 15:17
1.题目
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 scould also be considered as a subtree of itself.
Example 1:
Given tree s:
3 / \ 4 5 / \ 1 2Given tree t:
4 / \ 1 2Return 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 / 0Given tree t:
4 / \ 1 2Return false.
2.分析
题意很明确,就是判断给定的两个二叉树,后者是不是前者的子树,当然树是自己的子树,树形结构本身就是递归定义,所以一般首先想到的解法就是递归调用。
3.解题
我的解题:
public class Solution { public boolean isSubtree(TreeNode one, TreeNode two) { // 边界处理 Queue<TreeNode>s = new LinkedList<TreeNode>(); Queue<TreeNode>t = new LinkedList<TreeNode>(); if(one==null&&two==null){ return true; } if(one==null||two==null){ return false; } TreeNode a = one; TreeNode b = two; s.add(a); t.add(b); int flag = 0; while(!s.isEmpty()&&!t.isEmpty()){ TreeNode tema = s.poll(); TreeNode temb = t.poll(); if(tema.val!=temb.val){ flag = 1; break; } if(tema.left!=null){ s.add(tema.left); } if(tema.right!=null){ s.add(tema.right); } if(temb.left!=null){ t.add(temb.left); } if(temb.right!=null){ t.add(temb.right); } } if(flag!=1 && s.isEmpty() && t.isEmpty()){ return true; } return (isSubtree(one.left,two)||isSubtree(one.right,two)); }}
其他人解题:
public class Solution { public boolean isSubtree(TreeNode s, TreeNode t) { if (s == null) return false; if (isSame(s, t)) return true; return isSubtree(s.left, t) || isSubtree(s.right, t); } private boolean isSame(TreeNode s, TreeNode t) { if (s == null && t == null) return true; if (s == null || t == null) return false; if (s.val != t.val) return false; return isSame(s.left, t.left) && isSame(s.right, t.right); }}
4.总结
其实我的思路和大多数思路差不多,就是递归调用,判断树是否相等,一直递归直到满足递归结束条件,结束递归,得出最后的结果,只是觉得别人写得代码好简洁,而且采用在方法中再次递归替代了我里面的辅助空间。所以时间效率我可能高点,但是空间开销要大一些。
阅读全文
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
- Java中守护线程的总结
- nginx安装&tomcat集群
- 【hdu 1863】畅通工程(最小生成树&克鲁斯卡尔算法模板)
- libx264进行视频编码的流程
- spark RDD 五大特性
- 572. Subtree of Another Tree
- POJ 1287 Networking
- 【剑指offer】面试题57(1):和为S的数字
- 三大需求助ROS成为百度自动驾驶车载计算框架
- 机器学习笔记(3)——贝叶斯分类
- HDU 6069 素数筛+分解质因子
- 【JavaScript】js可以直接使用的鼠标经过切换图片
- 阿里云+wordpress搭建个人博客
- Numpy、Pandas和Matplotlib包基础知识