572. Subtree of Another Tree(python+cpp)
阿新 • • 發佈:2018-12-18
題目:
Given two non-empty binary trees
s
andt
, check whether treet
has exactly the same structure and node values with a subtree ofs
. A subtree ofs
is a tree consists of a node in s and all of this node’s descendants. The trees
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.
解釋:
t
是樹s
的子結構但是不是它的子樹。
判斷一棵樹是不是另一棵樹的子結構(ps:空樹不是任意一個樹的子結構),python程式碼:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution :
def HasSubtree(self, pRoot1, pRoot2):
# write code here
#判斷樹A以r為根節點的子樹是不是和樹B有相同的結構
def isSub(t1,t2):
if not t2:
return True
elif not t1:
return False
else:
return t1.val==t2.val and isSub(t1.left,t2.left) and isSub(t1.right,t2.right)
if not pRoot1 or not pRoot2:
return False
#在A中查詢與根結點一樣的結點
return isSub(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
需要用到100. Same Tree(python+cpp),注意上面的isSub()
和isSame()
有一些區別,isSub()
要求只要有部分結構相同就可以但是isSame()
要求整個結構的都要相同。
python程式碼:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def isSame(r1,r2):
if r1 and r2:
return r1.val==r2.val and isSame(r1.left,r2.left) and isSame(r1.right,r2.right)
return r1==r2
if not t:
return True
elif not s:
return False
return isSame(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t)
c++程式碼:
/**
* Definition for a binary tree node.
* 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 (!t)
return true;
else if(!s)
return false;
return isSame(s,t) or isSubtree(s->left,t) or isSubtree(s->right,t);
}
bool isSame(TreeNode*r1,TreeNode*r2)
{
if (r1 &&r2)
return r1->val==r2->val && isSame(r1->left,r2->left) &&isSame(r1->right,r2->right);
return r1==r2;
}
};
總結: 還有先把樹結構轉換成str再比較的,我還是覺得這種解法更經典一點。