程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode] Symmetric Tree

[LeetCode] Symmetric Tree

編輯:C++入門知識

[LeetCode] Symmetric Tree


 

Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

解題思路:

題目要求分別用遞歸法和迭代法做。

1、遞歸法。思路挺簡單,每次檢查一對節點,驗證這對節點的值是否相同,並且節點1的左孩子與節點2的右孩子的對稱的,並且節點1的右孩子與節點2的左孩子是對稱的。否則,返回false。

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return isSysmetricHelp(root, root);
    }
    
    bool isSysmetricHelp(TreeNode* root1, TreeNode* root2){
        if(root1==NULL && root2==NULL){
            return true;
        }
        if(root1==NULL || root2==NULL){
            return false;
        }
        if(root1->val != root2->val){
            return false;
        }
        return isSysmetricHelp(root1->left, root2->right)&&isSysmetricHelp(root1->right, root2->left);
    }
};
2、迭代法。有句話,遞歸轉化成非遞歸,無非就是用棧或堆來存儲中間狀態。我們用兩個隊列來存儲待比較的兩個節點即可。

 

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root==NULL){
            return true;
        }
        //兩個隊列的大小邏輯上一定相同
        queue left({root});
        queue right({root});
        while(!left.empty()){
            TreeNode* leftNode = left.front();
            TreeNode* rightNode = right.front();
            left.pop();
            right.pop();
            if(leftNode->val!=rightNode->val){
                return false;
            }
            if(leftNode->left!=NULL&&rightNode->right!=NULL){
                left.push(leftNode->left);
                right.push(rightNode->right);
            }else if(leftNode->left!=NULL || rightNode->right!=NULL){
                return false;
            }
            if(leftNode->right!=NULL&&rightNode->left!=NULL){
                left.push(rightNode->left);
                right.push(leftNode->right);
            }else if(leftNode->right!=NULL || rightNode->left!=NULL){
                return false;
            }
        }
        
        return true;
    }
};


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved