Reputation: 22123
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
Reputation: 1043
The problems with your solution are:
To fix your solution:
Another approach, if you can't destroy the tree:
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
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