Subtree

You have two every large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.

Have you met this question in a real interview? 
Yes
Example

T2 is a subtree of T1 in the following case:

       1                3
      / \              / 
T1 = 2   3      T2 =  4
        /
       4

T2 isn't a subtree of T1 in the following case:

       1               3
      / \               \
T1 = 2   3       T2 =    4
        /
       4
Note

A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

題目實際上是sameTree的變形,樹T2如果是另外樹T1的子樹,那麼在T1中一定可以找到一顆子樹與T2一樣,那就是說,我們可以遞歸的檢查,如果T1->val == T2->val,則應該檢查isSameTree(T1, T2);如果不相等,則還應該繼續遞歸檢查isSubTree(T1->left, T2) || is SubTree(T1->right, T2)。應該屬於常規的樹的問題,注意各個細節的考慮。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param T1, T2: The roots of binary tree.
     * @return: True if T2 is a subtree of T1, or false.
     */
    bool isSameTree(TreeNode *T1, TreeNode *T2)
    {
        if(T1 == NULL && T2 == NULL)
            return true;
        if(T1 == NULL || T2 == NULL)
            return false;
        if(T1->val != T2->val)
            return false;
        return isSameTree(T1->left, T2->left) && isSameTree(T1->right, T2->right);
    }
    
    bool isSubtree(TreeNode *T1, TreeNode *T2) {
        // write your code here
        if(T2 == NULL)
            return true;
        if(T1 == NULL)
            return false;
        
        if(T1->val == T2->val && isSameTree(T1, T2))
            return true;
            
        return isSubtree(T1->left, T2) || isSubtree(T1->right, T2);
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章