对称二叉树

递归写法:

class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot) {
        if (pRoot == NULL) {
            return true;
        }
        return IsSymmetrical(pRoot->left, pRoot->right);
    }
     
    bool IsSymmetrical(TreeNode* lt, TreeNode* rt) {
        if (lt == NULL && rt == NULL) {
            return true;
        }
        if (lt == NULL || rt == NULL) {
            return false;
        }
        return ( lt->val == rt->val && IsSymmetrical(lt->left, rt->right) && IsSymmetrical(lt->right, rt->left) );
    }
};

非递归写法:

class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot) {
        if (pRoot == NULL) {
            return true;
        }
        
        if (pRoot->left == NULL && pRoot->right == NULL) {
            return true;
        }
        
        if (pRoot->left == NULL || pRoot->right == NULL) {
            return false;
        }
        
        stack<TreeNode*> ltree;
        stack<TreeNode*> rtree;
        
        // 非递归遍历左、右子树
        // 左子树按根左右的顺序遍历,右子树按根右左的顺序遍历
        // 注意NULL节点也要存入栈中(特例:一棵树所有节点值都相等)
        ltree.push(pRoot->left);
        rtree.push(pRoot->right);
        while (!ltree.empty() && !rtree.empty()) {
            // 左子树
            TreeNode* cur1 = ltree.top(); ltree.pop();
            if (cur1 != NULL) {
                ltree.push(cur1->right);
                ltree.push(cur1->left);
            }
            // 右子树
            TreeNode* cur2 = rtree.top(); rtree.pop();
            if (cur2 != NULL) {
                rtree.push(cur2->left);
                rtree.push(cur2->right);
            }
            // 对称的话,应该取出的节点的值相等
            if (cur1 == NULL && cur2 == NULL) continue;
            if (cur1 == NULL || cur2 == NULL) return false;
            if (cur1->val != cur2->val) return false;
        }
        return ( (ltree.empty() && rtree.empty()) ? true : false);
    }

};
posted @ 2017-09-25 10:32  mioopoi  阅读(102)  评论(0编辑  收藏  举报