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:
귀속
void inorderTraversal(TreeNode *root,vector &res){
        if(root){
            inorderTraversal(root->left,res);
            res.push_back(root->val);
            inorderTraversal(root->right,res);
        }
    }
    vector inorderTraversal(TreeNode* root) {
        vector res;
        inorderTraversal(root,res);
        return res;
    }

해법 2:
창고를 이용하다
void inorderTraversal(TreeNode *root,vector &res){
        if(!root)
            return;
        
        stack st;
        while(!st.empty()||root){
            while(root){// 
                st.push(root);
                root=root->left;
            }// , 
            root=st.top();
            st.pop();
            res.push_back(root->val);
            root=root->right;
        }
    }

좋은 웹페이지 즐겨찾기