1. 程式人生 > >LeetCode——對稱二叉樹

LeetCode——對稱二叉樹

  迭代法:

bool Symmetric(TreeNode* left, TreeNode* right){
        bool bo1, bo2;
        if(left == NULL & right ==NULL)
            return true;
        else if(left == NULL | right ==NULL)
            return false;
        else if(left->val != right->val)
            return false;
        else if(left->val == right->val)
        {
            bo1 = Symmetric(left->left,right->right);
            bo2 = Symmetric(left->right,right->left);
            return bo1 & bo2;
        }
    }
    
    bool isSymmetric(TreeNode* root) {
        if(root == NULL)
            return true;
        
        TreeNode* left  = root->left;
        TreeNode* right = root->right;
        return Symmetric(left, right);
    }

遍歷:

類似於圖的BFS(寬度優先遍歷演算法),建議先閱讀【演算法入門】廣度/寬度優先搜尋(BFS)

 bool isSymmetric(TreeNode* root) {
        
        if(root == NULL)
            return true;
        
        queue<TreeNode*> que;
        
        que.push(root);
        que.push(root);
        
        while(!que.empty())
        {
            TreeNode* t1 = que.front();
            que.pop();
            TreeNode* t2 = que.front();
            que.pop();
            if (t1 == NULL & t2 == NULL) continue;
            if (t1 == NULL | t2 == NULL) return false;
            if (t1->val != t2->val) return false;
            que.push(t1->left);
            que.push(t2->right);
            que.push(t1->right);
            que.push(t2->left);
        }
        return true;      
}

標準庫queue:

                        queue.front()

                        queue.pop()

                        queue.push()