101. Symmetric Tree 對稱樹 (難點!)
阿新 • • 發佈:2019-02-14
https://leetcode.com/problems/symmetric-tree/
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
/** * 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 helper(root,root); } bool helper(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 helper(root1->left,root2->right) & helper(root1->right,root2->left); } };
非遞迴解法,用兩個佇列分別儲存左子樹節點和右子樹節點,每次從兩個佇列中分別取出元素,如果兩個元素的值相等,則繼續把他們的左右節點加入左右佇列。要注意每次取出的兩個元素,左佇列元素的左孩子要和右佇列元素的右孩子要同時不為空或者同時為空,否則不可能對稱,同理左佇列元素的右孩子要和右佇列元素的左孩子也一樣。
class Solution { public: bool isSymmetric(TreeNode* root) { if(root==NULL){ return true; } queue<TreeNode*> qleft; queue<TreeNode*> qright; if(root->left) qleft.push(root->left); if(root->right) qright.push(root->right); while(!qleft.empty() && !qright.empty()){ TreeNode* left=qleft.front();qleft.pop(); TreeNode* right=qright.front();qright.pop(); if(left->val==right->val){ if(left->left&&right->right){ qleft.push(left->left); qright.push(right->right); }else if(left->left || right->right){ return false; } if(left->right&&right->left){ qleft.push(right->left);// qright.push(left->right); }else if(left->right || right->left){ return false; } }else{ return false; } } return qleft.empty()&&qright.empty(); } };