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; } };