leetcode
来源:互联网 发布:巴萨拉菲尼亚数据 编辑:程序博客网 时间:2024/06/10 04:13
题目
Given two non-empty binary trees s andt, check whether tree t has exactly the same structure and node values with a subtree ofs. A subtree of s is a tree consists of a node ins 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.题意
给定两个非空的二叉树s , t 。判断t 是否准确存在于s中(结构和值都相同),即是s的子树。此处的子树定义为,s的一个结点以及该结点的所有后代。(s本身也可以看做自己的后代)
分析及解答
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); }}
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- 百练2795:金银岛题解
- LeetCode27 Remove Element
- JSTL标签中el表达式不起作用
- 近期杂文集锦-数学方法谈
- poj 2154 Color(polya + 欧拉函数)
- leetcode
- HUST1010 The Minimum Length
- 第一篇博客
- 初识nodejs3
- FAFU OJ 三角形
- j2me 一些常用函数总结
- 【Solr】深入浅出Solr(一)——搜索系统介绍
- java集合(Collection接口下的 List、Set 深入理解)
- 请通过代码实现以下功能:输入一个5X5的二维数组,将数组进行排序,其中一维数组按照平均值降序,一维数组内部升序排列。