前序:根左右
中序:左根右
后序:左右根
二叉树的非递归法使用栈来实现;
通常前序通过【根右左】的顺序压栈,进而保证出栈的顺序,而后序通过【根左右】的顺序压栈,出栈后再进行反转。
由于前序和后序先访问根节点,并且处理也是根节点,因此不需要额外指针的引用,但中序遍历不一样,访问和处理的节点顺序不同;
通过标记法解决,在要处理的节点后放入空节点作为标记,并单独处理,而前序:右左根,后序:根右左。
- /**
- * 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:
- TreeNode* mirrorTree(TreeNode* root) {
- if(root==NULL) return root;
- stack
st; - st.push(root);
- while(!st.empty()) {
- TreeNode* node = st.top();
- if(node != NULL) {
- st.pop();
- //前序:右左根
- //后序:根右左
- st.push(node);
- st.push(NULL);
- if(node->right) st.push(node->right);
- if(node->left) st.push(node->left);
- }
- else {
- st.pop();//弹出空节点
- node = st.top();
- st.pop();
- swap(node->left, node->right);
- }
- }
- return root;
- }
- };
层序遍历通过队列来实现。
直接上代码!
- class Solution {
- public:
- TreeNode* mirrorTree(TreeNode* root) {
- if(root==NULL) return root;
- queue
que; - que.push(root);
- while(!que.empty()) {
- int size = que.size();
- for(int i=0;i
- TreeNode* node = que.front();
- que.pop();
- swap(node->left, que->right);
- if(node->left) que.push(node->left);
- if(node->right) que.push(node->right);
- }
- }
- return root;
- }
- };