g
y
7
7
7
7

leetcode:94. 二叉树的中序遍历

94. 二叉树的中序遍历

给定一个二叉树,返回它的中序 遍历。

示例:

输入: 
[1,null,2,3] 1 \ 2 / 3 输出:
[1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

 

/**
 * 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 {
    vector<int>res;
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<pair<int,TreeNode*> >s;       
        s.push(pair(0,root));       //先把根节点压入  0代表没被访问过 1代表已经访问过
        while(!s.empty()){
            int color=s.top().first;
            TreeNode* t=s.top().second;
            s.pop();
            if(!t)continue;     //避免空指针
            if(color==0){    //如果当前节点没被访问过
                s.push(pair(0,t->right));    //中序遍历是左中右   先把右压入栈,这样他就在下边
                s.push(pair(1,t));         //不可以直接放到最终数组,因为访问其他节点还要用到。
                s.push(pair(0,t->left));     //倒序压入到栈里
            }else res.push_back(t->val);     //若已经被访问过,就把结果放到最终数组里
        }
        return res;
    }
};

  

posted @ 2020-03-18 17:03  gy77  阅读(100)  评论(0编辑  收藏  举报