二叉树非递归遍历


中序遍历

给出一棵二叉树,返回这棵树的中序遍历
例如:
给出的二叉树为{1,#,2,3},



typedef TreeNode Node;
class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector
     */
    vector inorderTraversal(TreeNode* root) {
        if(root==NULL) return {};
        // write code here
        stack stack;
        
        //左 -> 根 -> 右
        vector res;
        Node* f = root;
        while(stack.size() || f) {
            while(f) {
                stack.push(f),f = f->left;
            }
             
            f = stack.top();stack.pop();
            res.push_back(f->val);
            f = f->right;
              
            
        }
        return res;
        
        
    }
    
    
    
};

相关