给定一个二叉树的根节点 root ,返回它的 中序 遍历。
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
Python 解答:
1.递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def inOrder(root):
if not root:
return
else:
inOrder(root.left)
res.append(root.val)
inOrder(root.right)
inOrder(root)
return res
2.非递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
p = root
stack = []
while p or stack:
if p:
stack.append(p)
p = p.left
else:
temp = stack.pop()
res.append(temp.val)
if temp.right:
p = temp.right
return res
留言