My Accepted Answer with Recursive? Can we do iteratively?


  • 0
    J
        //vector<int> result;
    static vector<int> empty;
    
    void add_to_vector(TreeNode *root, vector<int> &vec){
        if(!root) return;
        vec.push_back(root -> val);
        if(root -> left) add_to_vector(root -> left, vec);
        if(root -> right) add_to_vector(root -> right, vec);
    }
    
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode *root) {
            if(!root) return empty;
            //TreeNode *cur = root;
            vector<int> result;
            add_to_vector(root, result);
            return result;
        }
    };

  • 0
    R

    Sure. Use DSF for graph.
    Here is my code in Python

    class Solution:
        # @param root, a tree node
        # @return a list of integers
        def preorderTraversal(self, root):
            if root is None: # empty tree
                return []
            discovered = []
            ans = []
            discovered.append(root)
            while discovered != []:
                v = discovered.pop()
                ans.append(v.val)
                if v.right is not None:
                    discovered.append(v.right)
                if v.left is not None:
                    discovered.append(v.left)
            return ans
    

Log in to reply
 

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