力扣的二叉树的中序遍历解法(Python3)

力扣的二叉树的中序遍历解法

题目描述:
给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
1

2
/
3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

参考程序1:

# 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]:
        stack = []
        result = []
        temp = root
        while stack or temp:
            if temp:
                stack.append(temp)
                temp = temp.left
            else:
                temp = stack.pop()
                result.append(temp.val)
                temp = temp.right
        return result

运行结果1:
力扣的二叉树的中序遍历解法(Python3)_第1张图片
参考程序2:

# 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 is None:
            return []
        else:
            result = []
            self.middle_digui(root, result)
        return result
    def middle_digui(self,root,result):
        if root == None:
            return
        self.middle_digui(root.left,result)
        result.append(root.val)
        self.middle_digui(root.right,result)

运行结果2:
力扣的二叉树的中序遍历解法(Python3)_第2张图片

你可能感兴趣的:(刷算法)