力扣 94. 二叉树的中序遍历 非递归版 栈

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
在这里插入图片描述

思路:非递归版,中序遍历——左根右,也就是把左子树遍历完再输出当前节点的值,然后进入右子树,这是一个递归的过程。所以提示我们需要用到循环找到最左侧的节点,然后输出它的值,进入它的右子树再重复上述过程。

/**
 * 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:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ans;
        if(root==NULL)
            return ans;
        stack<TreeNode*> stk;
        TreeNode *cur=root;
        while(!stk.empty()||cur){
            while(cur){
                stk.push(cur);
                cur=cur->left;
            }
            cur=stk.top();
            stk.pop();
            ans.push_back(cur->val);
            cur=cur->right;
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章