[LeetCode] 非递归中序遍历二叉树 non recursive inorder traversal

非递归中序遍历二叉树 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;
        
    }


上面的代码和非递归前序遍历几乎一样。

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值