• LintCode 子树


    easy 子树

    19%
    通过

    有两个不同大小的二进制树: T1 有上百万的节点; T2 有好几百的节点。请设计一种算法。判定 T2 是否为 T1的子树。

    您在真实的面试中是否遇到过这个题? 
    Yes
    例子

    以下的样例中 T2 是 T1 的子树:

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

    以下的样例中 T2 不是 T1 的子树:

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

    /**
     * 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 isSubtree(TreeNode *T1, TreeNode *T2) {
             bool result  = false;
            if (T2 == nullptr) {
                return true;
            }
            if (T1 == nullptr) {
                return false;
            }
            // write your code here
            if (T1->val == T2->val) {
                 result = dp(T1,T2);
            }
            if (!result) {
              result =  isSubtree(T1->left,T2);
            }
            if (!result) {
                result =  isSubtree(T1->right,T2);
            }
            return result;
        }
        
        bool dp (TreeNode *T1, TreeNode *T2) {
        
            if (T1 != nullptr && T2!=nullptr && T1->val == T2->val) {
                return dp(T1->left,T2->left) && dp (T1->right,T2->right);
            }
            if (T1 == nullptr && T2 == nullptr) {
                return true;
            }
            return false;
        }
    };
    


  • 相关阅读:
    超有爱的并查集
    写给想当程序员的朋友
    POJ 1961 字符串 KMP (i-next[i])
    POJ 2406 KMP算法next数组理解
    POJ 2387 Bellman双重边
    POJ 1917 字符串替换
    POJ 1062 坑爹的聘礼(枚举等级差选择性找边)
    Linux下libxml2的使用
    浙大pat 1003
    判定一棵二叉树是否是二叉搜索树
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5377536.html
Copyright © 2020-2023  润新知