A Esay-understand C++ Solution


  • 2
    Y
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> ans;
            if(root == NULL) return ans;
            stack<TreeNode*> st;
            while((root != NULL)||(st.size() != 0)) {
                ans.push_back(root->val);
                if(root->right != NULL) st.push(root->right);
                if(root->left != NULL) root = root->left;
                else if(st.size() != 0) {
                        root = st.top();
                        st.pop();
                    } else root = NULL;
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.