非递归中序遍历二叉树 non recursive inorder traversal
非递归前序遍历,参看这里。
用两个 while 循环来做, 思路如下.
1) Create an empty stack S. 2) Initialize current node as root 3) Push the current node to S and set current = current->left until current is NULL 4) If current is NULL and stack is not empty then a) Pop the top item from stack. b) Print the popped item, set current = popped_item->right c) Go to step 3. 5) If current is NULL and stack is empty then we are done.
下面的代码经过简单修改,可以完成逆中序遍历,即先访问右子树,再访问根节点,最后访问左子树。
vector<int> inorderTraversal(TreeNode *root) { vector<int> vec; // stores the preorder sequence stack<TreeNode*> st; // auxiliary stack TreeNode* curr = root; while(1) { while(curr) { st.push(curr); curr = curr->left; } if(st.size()==0) break; else { curr = st.top(); st.pop(); vec.push_back(curr->val); curr = curr->right; } } return vec; }
上面的代码和非递归前序遍历几乎一样。