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 Inorder Traversal #22

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

Binary Tree Inorder Traversal #22

cheatsheet1999 opened this issue Sep 8, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

Given the root of a binary tree, return the inorder traversal of its nodes' values.

Screen Shot 2021-09-07 at 11 00 18 PM

Screen Shot 2021-09-07 at 11 00 47 PM

Recursive Solution

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

O(n) iterative solution is awesome!

/*
As long as there is root or stack has length, we loop over. 
In the loop, if there is a root, we push root into stack and go see the left, 
until there is no root on left subtree,  then we find the nearest last root,
and put it into stack, then loop the right subtree.
*/
var inorderTraversal = function(root) {
    let stack = [];
    let res = [];
    while(root || stack.length) {
        if(root) {
            stack.push(root);
            root = root.left;
        } else {
            //find the nearst root
            root = stack.pop();
            res.push(root.val);
            root = root.right;
        }
    }
    return res
}
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