【力扣100】94.二叉树的中序遍历

添加链接描述

# 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: Optional[TreeNode]) -> List[int]:
        def dfs(root,res):
            if not root:
                return
            dfs(root.left,res)
            res.append(root.val)
            dfs(root.right,res)

        res=[]
        dfs(root,res)
        return res
# 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: Optional[TreeNode]) -> List[int]:
        # 迭代法:一个栈,一个接收结果数组
        if not root:
            return []
        stack=[]
        res=[]
        # 思路是一直把最左边的节点加入栈中
        while root or stack:
            if root:
                stack.append(root)
                root=root.left
            else:
                cur=stack.pop()
                res.append(cur.val)
                root=cur.right
        return res    

非迭代法思路:

  1. 确认中序遍历的顺序:左中右
  2. 不太好理解,但是走一遍代码,就知道他在干什么,哈哈

你可能感兴趣的:(leetcode,算法,职场和发展)