zoukankan      html  css  js  c++  java
  • 对称二叉树

    递归写法:

    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);
        }
    
    };
    
  • 相关阅读:
    LeetCode59 Spiral Matrix II
    LeetCode58 Length of Last Word
    LeetCode54 Spiral Matrix
    LeetCode63 Unique Paths II
    LeetCode62 Unique Paths
    LeetCode55 Jump Game
    网易2017年校招笔试题 最大的奇约数
    Codeforces Round #119 (Div. 2)
    Codeforces Round #118 (Div. 2)
    2016 MIPT Pre-Finals Workshop Taiwan NTU Contest
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/7590736.html
Copyright © 2011-2022 走看看