美文网首页
leetcode 面试题 04.10. 检查子树

leetcode 面试题 04.10. 检查子树

作者: Source_Chang | 来源:发表于2020-10-26 00:54 被阅读0次

    leetcode

    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 checkSubTree(TreeNode* t1, TreeNode* t2) {
    
            if ( !t1 || !t2 ) {
    
                return false;
            }
    
            if ( t1 -> val == t2 -> val ) {
    
                return checkEqual( t1, t2 );
    
            } else {
    
                if ( t1 -> left && checkSubTree( t1 -> left, t2 ) ) {
    
                    return true;
                }
    
                if ( t1 -> right && checkSubTree( t1 -> right, t2 ) ) {
    
                    return true;
                }
    
                return false;
            }
        }
    
        bool checkEqual(TreeNode* t1, TreeNode* t2) {
    
            if ( !t1 && !t2 ) {
    
                return true;
            }
    
            if ( !t1 || !t2 ) {
    
                return false;
            }
    
            return t1 -> val == t2 -> val && checkEqual( t1 -> left, t2 -> left ) && checkEqual( t1 -> right, t2 -> right );
        }
    };
    

    相关文章

      网友评论

          本文标题:leetcode 面试题 04.10. 检查子树

          本文链接:https://www.haomeiwen.com/subject/ehvomktx.html