Wizard
Wizard

Reputation: 22123

Binary Tree Inorder Traversal

I wrote such a solution to Binary Tree Inorder Traversal - LeetCode

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderTraversal(self, root: "TreeNode") -> "List[int]":
        stack, res = [root], []

        while stack:
            cur = stack[-1]
            cur = cur.left

            if cur == None:
                cur = stack.pop()
                res.append(cur.val)
                cur = cur.right 
            else:
                stack.append(cur)
                cur = cur.left 
        return res 

but did not work as expected

Finished
Runtime: 48 ms
Your input  [1,null,2,3]
Output  [1]
Expected  [1,3,2]

What's the problem with my solution?

Upvotes: 0

Views: 354

Answers (2)

Shuki Avraham
Shuki Avraham

Reputation: 1043

The problems with your solution are:

  • if you don't have a left, you print the node and returning from the sub-tree without going right
  • if you have a left, you append it. that can cause an infinite loop (when you'll return from the left you'll append it again)

To fix your solution:

  • if you don't have a left, print the node and put the right on the stack
  • if you have a left, put the left on the stack and remove the left pointer from the TreeNode so you won't add it again upon returning.

Another approach, if you can't destroy the tree:

  • go all the way left, putting all the nodes along the way on the stack
  • when removing a node from the stack, print it, go right and then all the way left, putting all the nodes on the stack.

class Solution:

def inorderTraversal(self, root: "TreeNode") -> "List[int]":
    stack, res = [root], []
    cur = stack[-1]
    while cur.left != None:
        stack.append(cur.left)
        cur = cur.left 
    while stack:
        cur = stack.pop()
        res.append(cur.val)
        if cur.right != None:
            stack.append(cur.right)
            cur = cur.right
            while cur.left != None:
                stack.append(cur.left)
                cur = cur.left 
    return res 

Upvotes: 2

Xiidref
Xiidref

Reputation: 1531

The solution when you write code with tree is very oftent to use recursion in your case the code that you search for would be :

def inorderTraversal(root):
    result = []
    if root.left != None:
        result.extend(inorderTraversal(root.left))
    result.append(root.val)
    if root.right != None:
        result.extend(inorderTraversal(root.right))
    return result

If it is unclear please ask me, i will add more precision

Upvotes: 0

Related Questions