[英]Binary Tree Inorder Traversal
I wrote such a solution to Binary Tree Inorder Traversal - LeetCode 我为二叉树有序遍历编写了这样的解决方案-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? 我的解决方案有什么问题?
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
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 : 当您使用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
If it is unclear please ask me, i will add more precision 如果不清楚,请问我,我会增加精度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.