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.


這道題剛開始自己想的時候想錯了,應該是,如果root的value相同的話,判斷s和t是否是same tree,如果不同的話,判斷s->left和t或者s->right和t是不是subtree,並且這些條件是並列的或關係,而不是if else的關係,任意滿足一個就可以了。

Runtime: 36 ms, faster than 22.81% of C++ online submissions for Subtree of Another Tree.

Memory Usage: 21.1 MB, less than 56.25% of C++ online submissions for Subtree of Another Tree.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
 */
class Solution {
public:
    bool isSame(TreeNode* s, TreeNode* t) {
        if (!s || !t) {
            return !s && !t;
        }
        if (s->val != t->val) {
            return false;
        }
        return isSame(s->left, t->left) && isSame(s->right, t->right);
    }
    
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if (!s || !t) {
            return !s && !t;
        }
        if (isSame(s, t)) {
            return true;
        }
        // cannot use if-else because if parent is not same, child can be same
        return isSubtree(s->left, t) || isSubtree(s->right, t);
    }
};

好像還有一種方法但是不想看了。

發佈了123 篇原創文章 · 獲贊 1 · 訪問量 9376
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章