1. 程式人生 > >LintCode - Binary Tree Inorder Traversal

LintCode - Binary Tree Inorder Traversal

解法一 recursion

class Solution {
public:
    vector<int> res;
    vector<int> inorderTraversal(TreeNode * root) {
        res.clear();
        helper(root);
        return res;
    }
    void helper(TreeNode* root){
        if(!root) return;
        helper(root->left);
        res.push_back(root->val);
        helper(root->right);
    }
};

解法二 non-recursion

class Solution {
public:
    vector<int> inorderTraversal(TreeNode * root) {
        stack<TreeNode*> st;
        vector<int> res;
        TreeNode* cur = root;
        
        while(cur || !st.empty()){
            //left
            while(cur){
                st.push(cur);
                cur = cur->left;
            }
            //visit
            TreeNode* t = st.top(); st.pop();
            res.push_back(t->val);
        
            //right
            cur = t->right;
        }
        return res;
        
    }
};
class Solution {
public:
    vector<int> inorderTraversal(TreeNode * root) {
        // write your code here
        stack<TreeNode*> st;
        vector<int> res;
        //left
        while(root){
            st.push(root);
            root = root->left;
        }
        while(!st.empty()){
            //visit
            TreeNode* t = st.top(); st.pop();
            res.push_back(t->val);
            
            //right
            if(t->right) {
                TreeNode* node = t->right;
                //left
                while(node){
                    st.push(node);
                    node = node->left;
                }
            }
            
        }
        return res;
    }
};