LeetCode 572. Subtree of Another Tree (是否是另一个树的子树)

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   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.
 
 

题目标签:Tree

  这道题目给了我们两个二叉树s, t,让我们判断一下,t 是不是 s 的子树。首先我们想一下,如果 s 和 t 一摸一样,那么 t 也是 s 的子树。如果s和t不一样, 那么我们要依次从 s 的 left 当作一个新的树,和 t 比较,如果不是;从 s 的 right 当作一个新的树,和 t 比较。直到把 s 树遍历结束;其中如果遇到 s 等于 t 的情况,立即返回true即可。那么我们要另外设一个function,来判断一下是否两个二叉树是相同的。

 

Java Solution:

Runtime beats 83.10% 

完成日期:06/30/2017

关键词:Tree

关键点:recursively call trick:

  recursively - return function(left) || function(right) : 只需要两个中任何一个function call 的返回值是true,那么答案就是true,运用在遍历 s 树的每一个点 和 t 比较;

  recursively - return function(left) && function(right): 需要两个children都是返回true, 答案才是true,运用在判断两颗树否则相同。

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution 
11 {
12     public boolean isSubtree(TreeNode s, TreeNode t) 
13     {
14         if(s == null)
15             return false;
16         
17         if(isSame(s,t)) // check is tree s and t are same
18             return true;
19         
20         // if tree s and t are not same, recursively call to pass s children
21         return isSubtree(s.left, t) || isSubtree(s.right, t);
22     }
23     
24     public boolean isSame(TreeNode s, TreeNode t)
25     {
26         if(s == null && t == null) // if two nodes are null, they are same
27             return true;
28         
29         if(s == null || t == null) // if one node is null, another is not null, they are not same
30             return false;
31         
32         if(s.val != t.val) // if two node values are not same
33             return false;
34         
35         // if two node values are same, continue to check their children until end of tree
36         return isSame(s.left, t.left) && isSame(s.right, t.right);
37     }
38 }

参考资料:

http://www.cnblogs.com/grandyang/p/6828687.html

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

posted @ 2017-06-30 23:05  Jimmy_Cheng  阅读(675)  评论(0编辑  收藏  举报