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);
        }
    
    };
    
  • 相关阅读:
    程序员通过什么渠道接外包项目
    中小型软件项目开发一般流程建议
    DevExpress GridControl功能总结
    页面UI注意事项,你在乎吗?
    加密,解密
    本地化(国际化)
    AutoLayout(自动布局)
    UItableView与UICollectionView
    分享iOS开发常用(三方类库,工具,高仿APP,实用网站,技术干货)
    NSPredicate
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/7590736.html
Copyright © 2011-2022 走看看