LeetCode 94:Binary Tree Inorder Traversal(中序遍历)

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

1
\
2
/
3

return [1,3,2].
题目要求对二叉树进行非递归的中序遍历,所谓中序遍历即,先访问左子树、再访问根节点、然后是右子树。通常采用递归的方法,题目要求采用非递归的方法实现。算法如下:

1)如果根节点非空,将根节点加入到栈中。

2)如果栈不空,取栈顶元素(暂时不弹出),

 如果左子树已访问过,或者左子树为空,则弹出栈顶节点,将其值加入数组,如有右子树,将右子节点加入栈中。
 如果左子树不为空,切未访问过,则将左子节点加入栈中,并标左子树已访问过。

3)重复第二步,直到栈空。

代码如下:

//包裹结构体,标明左子树是否已经访问过
 struct TreeNodeWrapper{
    struct TreeNode *pNode;
    bool lVisited; //左子树已访问过
    bool rVisited; //右子树已访问过
    TreeNodeWrapper(TreeNode * p){pNode = p; lVisited= false; rVisited= false;}
};
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
               vector<int> result;
        stack<TreeNodeWrapper*> node_stack;
        if (root == NULL)
               return result;
        node_stack.push(new TreeNodeWrapper(root));
        while(!node_stack.empty()){
            TreeNodeWrapper* pNode = node_stack.top();
            if (pNode->lVisited || pNode->pNode->left==NULL) //左子树已访问过,或者为空
            {
                node_stack.pop();
                result.push_back(pNode->pNode->val); //访问节点,访问右子树
                if (pNode->pNode->right) 
                {
                    node_stack.push(new TreeNodeWrapper(pNode->pNode->right));
                }
                delete pNode;
            }else{      //访问左子树,并标记
                node_stack.push(new TreeNodeWrapper(pNode->pNode->left));
                pNode->lVisited = true;
            }
        }
        return result;
    }
};

方法二,不使用包裹结构体。上面的解法虽然原理上比较简单,当使用了一个包裹结构体,和大量的New/delete操作,显得比较复杂。不如下面这种算法比较简洁。

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
       vector<int> result;
        stack< TreeNode *> node_stack;
        TreeNode * pNode = root;
        while (pNode || !node_stack.empty()) {
             //节点不为空,加入栈中,并访问节点左子树
             if (pNode != NULL) {
                node_stack.push(pNode);
                pNode = pNode->left;
            }else{
             //节点为空,从栈中弹出一个节点,访问这个节点,
                pNode = node_stack.top();
                node_stack.pop();
              //访问节点右子树
                result.push_back(pNode->val);
                pNode = pNode->right;
            }
        }
        return result; 
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值