diff --git a/solutions/101. Symmetric Tree.md b/solutions/101. Symmetric Tree.md index abba02c..5ce2db9 100644 --- a/solutions/101. Symmetric Tree.md +++ b/solutions/101. Symmetric Tree.md @@ -8,6 +8,8 @@ ## 思路二: 非递归 采用类似层次遍历的方法。对于左子树从上往下**从左往右**层次遍历,对于右子树从上往下**从右往左**层次遍历,遍历过程中进行比较。注意遍历过程中如果某个节点的孩子为空也应将其孩子入队。 +层次遍历用的队列,其实用栈也是可以的,代码几乎一样,这样就是分别用**根右左**和**根左右**来遍历左右子树,同理空孩子也需要入栈。 + 两种思路都相当于遍历一遍树,所以两种思路的时空复杂度均为O(n)。 # C++ @@ -32,23 +34,31 @@ public: ``` C++ class Solution { public: -bool isSymmetric(TreeNode *root) { - if (!root) return true; + bool isSymmetric(TreeNode* root) { + if(!root) return true; + + queuecontainer1, container2; // use queue + // stackcontainer1, container2; // use stack - TreeNode *left, *right; - queue q1, q2; - q1.push(root->left); - q2.push(root->right); - - while (!q1.empty() && !q2.empty()){ - left = q1.front(); q1.pop(); - right = q2.front(); q2.pop(); - if (!left && !right) continue; - if (!left || !right || left->val != right->val) return false; - q1.push(left->left); - q1.push(left->right); - q2.push(right->right); - q2.push(right->left); + container1.push(root -> left); + container2.push(root -> right); + + TreeNode *p1, *p2; + while(!container1.empty() && !container2.empty()){ + p1 = container1.front(); p2 = container2.front(); // use queue + // p1 = container1.top(); p2 = container2.top(); // use stack + + 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; }