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

A decent way to do real iterative tree traversal #2

Open
csujedihy opened this issue Jun 20, 2017 · 1 comment
Open

A decent way to do real iterative tree traversal #2

csujedihy opened this issue Jun 20, 2017 · 1 comment
Labels

Comments

@csujedihy
Copy link
Owner

csujedihy commented Jun 20, 2017

For three different kinds of traversal, we only need to change the order of tuples in one line just like what we've done in the recursive solution which is very decent and classical. Just put (0, p[1]) in different order!

The idea is from my former lab-mate and it's actually a BFS but changing the order on queue when traversing to emulate DFS.

For post-order traversal:

def postorderTraversal(self, root):
    res, stack = [], [(1, root)]
    while stack:
        p = stack.pop()
        if not p[1]: continue
        stack.extend([(0, p[1]), (1, p[1].right), (1, p[1].left)]) if p[0] != 0 else res.append(p[1].val)
    return res

For in-order traversal:

def inorderTraversal(self, root):
    res, stack = [], [(1, root)]
    while stack:
        p = stack.pop()
        if not p[1]: continue
        stack.extend([(1, p[1].right), (0, p[1]), (1, p[1].left)]) if p[0] != 0 else res.append(p[1].val)
    return res

For pre-order traversal:

def preorderTraversal(self, root):
    res, stack = [], [(1, root)]
    while stack:
        p = stack.pop()
        if not p[1]: continue
        stack.extend([(1, p[1].right), (1, p[1].left), (0, p[1])]) if p[0] != 0 else res.append(p[1].val)
    return res
@csujedihy csujedihy added the Note label Jun 20, 2017
@chu-tianshu
Copy link

chu-tianshu commented Aug 27, 2017

Amazing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants