Simple recursive solution sharing (C++) (0 ms)


  • 1
    A
    class Solution {
    public:
        vector<int> result;
        vector<int> preorderTraversal(TreeNode* root) {
            if(root)
            {
                result.push_back(root->val);
                preorderTraversal(root->left);
                preorderTraversal(root->right);
            }
            return result;
        }
    };

  • 0
    R

    iterative solution, using stack.seeming there is always a way could transform recursive solution into iterative solution with a stack.

    vector<int> preorderTraversal(TreeNode* root) {
    	vector<int> res;
    	if(NULL==root)
    		return res;
    
    	stack<TreeNode *> st;
    	st.push(root);
    	while(!st.empty()){
    		auto node=st.top();
    		st.pop();
    		if(node->right) st.push(node->right);
    		if(node->left) st.push(node->left);
    		res.push_back(node->val);
    	}
    	return res;
    }

Log in to reply
 

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