题目描述
给定一个二叉树,返回它的中序 遍历。
中序遍历是怎么回事
永远先返回左儿子节点的值,再返回中间值,再返回右儿子节点的值
递归
# 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]:
output=[]
def hanshu(root):
if not root:
return
hanshu(root.left)
output.append(root.val)
hanshu(root.right)
hanshu(root)
return output
执行用时 :40 ms, 在所有 Python3 提交中击败了40.72%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.28%的用户
迭代
# 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]:
# if root:
# stack=[root]
# else
# return
stack=[]
output=[]
while stack or root:
while root: #持续向左儿子节点靠拢
stack.append(root)
root=root.left
root=stack.pop() #到最左下角的儿子节点
output.append(root.val) #把中间值放入结果数列中
root=root.right #提供右儿子节点,再返回上面继续搜索左儿子节点
return output
要弄两个循环,当初只想到用一个循环,然后死活不知道怎么做
执行用时 :36 ms, 在所有 Python3 提交中击败了61.46%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.28%的用户