Monday, September 4, 2017

101. Symmetric Tree

https://leetcode.com/problems/symmetric-tree/description/
Solution 1. Recursion.
    bool compareNodes(TreeNode* ln, TreeNode* rn) {
        if(!ln && !rn) return true;
        if(!ln || !rn || ln->val != rn->val) return false;
        return compareNodes(ln->left, rn->right) && compareNodes(ln->right, rn->left);
    }
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        return compareNodes(root->left, root->right);
    }
Solution 2. Iteration. Need to take care of the case when ln->left =null and rn->left=null.
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        TreeNode *ln, *rn;
        stack<TreeNode*> lst, rst;
        lst.push(root->left);
        rst.push(root->right);
        while(!lst.empty() && !rst.empty()) {
            ln = lst.top();
            lst.pop();
            rn = rst.top();
            rst.pop();
            if(!ln && !rn) continue;
            if(!ln || !rn || ln->val != rn->val) return false;
            lst.push(ln->right);
            lst.push(ln->left);
            rst.push(rn->left);
            rst.push(rn->right);
        }
        if(!lst.empty() || !rst.empty()) return false;
        return true;
    }

No comments:

Post a Comment