我为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
但未按预期工作
Finished
Runtime: 48 ms
Your input [1,null,2,3]
Output [1]
Expected [1,3,2]
我的解决方案有什么问题?
答案 0 :(得分:2)
您的解决方案存在的问题是:
要解决您的解决方案,请执行以下操作:
另一种方法,如果您无法破坏树:
类解决方案:
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
答案 1 :(得分:0)
当您使用tree编写代码时,解决方案非常倾向于在您要搜索的代码为的情况下使用递归:
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
如果不清楚,请问我,我会提高精度