leetCode第94题 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[2,1]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
二叉树的中序遍历就是左->中->右的顺序。
当访问左的时候,同样是以左作为新的根节点然后进行左->中->右的遍历。
不难看出,中序遍历本身就是一个递归的遍历。
题目的输出是一个列表之类的东西,所以遍历时应该把每一个值先进行一个存放。
------------------------
递归进行中序遍历
当root为None时直接返回
先遍历左边
在列表中加入root的值
遍历右边
## python3
# 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]) -> []:
result = []
self.accessTree(root,result)
return result
def accessTree(self, root: [TreeNode],result : list) :
if root == None:
return
self.accessTree(root.left,result)
result.append(root.val)
self.accessTree(root.right,result)
进阶,使用循环进行中序遍历
使用循环进行中序遍历时,需要借用另一种数据结构:栈,因为循环经过数的结点时会丢失根节点的位置,所以要借助栈事先存放好根节点。然后不断记录左子树的根节点,之后一个一个pop出来。
## python3
class Solution:
def inorderTraversal(self, root: [TreeNode]) -> []:
result = [] ## 存放结果的列表
stack = [] ## 存放中间结点的栈
while root != None or len(stack) != 0: #只有root和栈都为空时才算遍历完
while root != None:
stack.append(root)
root = root.left
root = stack.pop()
result.append(root.val)
root = root.right
return result
用循环没有递归来的快
同样的方法,python的执行效率比其它语言慢的多