mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
update code of solution2
This commit is contained in:
parent
c1fb25f6d2
commit
e3c5873d3b
@ -8,6 +8,8 @@
|
|||||||
## 思路二: 非递归
|
## 思路二: 非递归
|
||||||
采用类似层次遍历的方法。对于左子树从上往下**从左往右**层次遍历,对于右子树从上往下**从右往左**层次遍历,遍历过程中进行比较。注意遍历过程中如果某个节点的孩子为空也应将其孩子入队。
|
采用类似层次遍历的方法。对于左子树从上往下**从左往右**层次遍历,对于右子树从上往下**从右往左**层次遍历,遍历过程中进行比较。注意遍历过程中如果某个节点的孩子为空也应将其孩子入队。
|
||||||
|
|
||||||
|
层次遍历用的队列,其实用栈也是可以的,代码几乎一样,这样就是分别用**根右左**和**根左右**来遍历左右子树,同理空孩子也需要入栈。
|
||||||
|
|
||||||
两种思路都相当于遍历一遍树,所以两种思路的时空复杂度均为O(n)。
|
两种思路都相当于遍历一遍树,所以两种思路的时空复杂度均为O(n)。
|
||||||
|
|
||||||
# C++
|
# C++
|
||||||
@ -35,20 +37,28 @@ public:
|
|||||||
bool isSymmetric(TreeNode* root) {
|
bool isSymmetric(TreeNode* root) {
|
||||||
if(!root) return true;
|
if(!root) return true;
|
||||||
|
|
||||||
TreeNode *left, *right;
|
queue<TreeNode *>container1, container2; // use queue
|
||||||
queue<TreeNode*> q1, q2;
|
// stack<TreeNode *>container1, container2; // use stack
|
||||||
q1.push(root->left);
|
|
||||||
q2.push(root->right);
|
|
||||||
|
|
||||||
while (!q1.empty() && !q2.empty()){
|
container1.push(root -> left);
|
||||||
left = q1.front(); q1.pop();
|
container2.push(root -> right);
|
||||||
right = q2.front(); q2.pop();
|
|
||||||
if (!left && !right) continue;
|
TreeNode *p1, *p2;
|
||||||
if (!left || !right || left->val != right->val) return false;
|
while(!container1.empty() && !container2.empty()){
|
||||||
q1.push(left->left);
|
p1 = container1.front(); p2 = container2.front(); // use queue
|
||||||
q1.push(left->right);
|
// p1 = container1.top(); p2 = container2.top(); // use stack
|
||||||
q2.push(right->right);
|
|
||||||
q2.push(right->left);
|
container1.pop(); container2.pop();
|
||||||
|
|
||||||
|
if(p1 && p2){
|
||||||
|
if(p1 -> val != p2 -> val) return false;
|
||||||
|
container1.push(p1 -> left);
|
||||||
|
container1.push(p1 -> right);
|
||||||
|
container2.push(p2 -> right);
|
||||||
|
container2.push(p2 -> left);
|
||||||
|
}
|
||||||
|
else if(!p1 && !p2) continue;
|
||||||
|
else return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user