LeetCode Subtree of Another Tree
来源:互联网 发布:软件系统的可靠性 编辑:程序博客网 时间:2024/05/22 01:50
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 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 2
Return false.
题解:此题是给定两棵树,判断第二棵树是否为第一课二叉树的子树。我先写了一个方法用来判断给定的两棵二叉树是否相同,然后我又写了一个方法采用先序遍历,来得到第一棵二叉树中的那些和第二棵二叉树的根节点的值相同的所有节点,将它们保存在一个arraylist中,然后在主函数中,采用遍历此arraylist的方法,将每一次得到的节点和第二棵二叉树进行是否相同比较,直到遍历完这个arraylist,当然如果中途发现某个节点的子树和第二棵二叉树完全相同,那么就直接输出true;否则遍历完arraylist都没有发现子树,那么就直接输出false。
public class isSubtree{ public boolean isSubtree(TreeNode s,TreeNode t) { ArrayList<TreeNode> list = new ArrayList<>(); if(s == null && t == null) return true; if(s != null && t == null) return false; if(s == null && t != null) return false; else { preOrder(s,t.val,list); int length = list.size(); while(length-- > 0) { if(subtree(list.get(0),t) == true) return true; else list.remove(0); } } return false; } public boolean subtree(TreeNode s1,TreeNode s2) //用来判断是否是相同的两棵二叉树 { if(s1 == null && s2 == null) return true; if(s1 == null && s2 != null) return false; if(s1 != null && s2 == null) return false; if(s1.val == s2.val) return subtree(s1.left,s2.left) && subtree(s1.right,s2.right); else return false; } public void preOrder(TreeNode root,int target,ArrayList<TreeNode> list) //采用先序遍历的方法来将第一棵二叉树中和第二棵二叉树的根节点的值相同的节点保存到一个arraylist中 { if(root == null) return; if(root.val == target) list.add(root); preOrder(root.left,target,list); preOrder(root.right,target,list); }}
阅读全文
0 0
- LeetCode: Subtree of Another Tree
- leetcode : subtree of another tree
- LeetCode Subtree of Another Tree
- [LeetCode] Subtree of Another Tree
- 【LeetCode】Subtree of Another Tree 解题报告
- [LeetCode]572. Subtree of Another Tree
- [leetcode]: 572. Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- [leetcode: Python]572. Subtree of Another Tree
- [leetcode]572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- [LeetCode] 572. Subtree of Another Tree
- LeetCode-572. Subtree of Another Tree (Java)
- Leetcode-572. Subtree of Another Tree
- LeetCode 572 Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- [LeetCode]572. Subtree of Another Tree
- 一些自己不会的小函数用法
- UCOSII启动流程详解(结合源码分析)
- layUi框架入门篇(三)
- 网页编程--JavaScript之function()
- 数据库事物的四大特性
- LeetCode Subtree of Another Tree
- Error:org.gradle.api.internal.changedetection.state.DefaultFileCollectionSnapshotter
- 网络流24题-13
- [莫队]luogu3674 小清新人渣的本愿
- Upgrade to Oracle Database 12c OCP 1z0-060 No.1
- archlinux安装教程以及自己踩过的坑
- setsockopt :SO_LINGER 选项设置
- Linux常用操作命令
- 3000 fps代码运行步骤详解(C++)