Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary Tree Preorder Traversal #21

Open
cheatsheet1999 opened this issue Sep 8, 2021 · 0 comments
Open

Binary Tree Preorder Traversal #21

cheatsheet1999 opened this issue Sep 8, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

cheatsheet1999 commented Sep 8, 2021

Given the root of a binary tree, return the preorder traversal of its nodes' values.
Screen Shot 2021-09-07 at 7 30 44 PM
Screen Shot 2021-09-07 at 7 31 39 PM

A Very Straightforward Solution

var preorderTraversal = function(root, res = []) {
    if (!root) return [];
    res.push(root.val);
    if(root.left)  preorderTraversal(root.left, res);
    if(root.right) preorderTraversal(root.right, res);
    return res;
};

An O(N) Solution may be interesting

var preorderTraversal = function(root) {
    if(!root) return [];
    //We need to put a root in the stack first, because Pre-order traverse from root => left => right
    let stack = [root];
    let arr = [];
    while(stack.length) {
        let curr = stack.pop();
        arr.push(curr.val);
        // we want to push right subtree is because the left subtree will be visit first then.
        if(curr.right) {
            stack.push(curr.right);
        }
        if(curr.left) {
            stack.push(curr.left);
        }
    }
    return arr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant