1 2 3 4 5 6 7 8 9 10 11 12 13 |
给定一个二叉树,返回它的中序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? |
首先,我们要县弄明白什么叫中序遍历:就是先左节点,然后中节点,然后右节点
利用递归其实很简单
核心逻辑:
判断是否有左节点
中间节点处理
判断是否有右节点
(核心就是左侧的全部放进取,然后放根结点,然后放右侧节点)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ answer = [] def inorder(root): if root == None: return None if root.left != None: inorder(root.left) answer.append(root.val) if root.right != None: inorder(root.right) inorder(root) return answer |
代码参考:
https://blog.csdn.net/fuxuemingzhu/article/details/79294461
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021