0094-leetcode算法实现之二叉树中序遍历-binary-tree-inorder-traversal-python&golang实现

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

示例 1:
0094-leetcode算法实现之二叉树中序遍历-binary-tree-inorder-traversal-python&golang实现

输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [1]
输出:[1]
示例 4:
0094-leetcode算法实现之二叉树中序遍历-binary-tree-inorder-traversal-python&golang实现

输入:root = [1,2]
输出:[2,1]
示例 5:
0094-leetcode算法实现之二叉树中序遍历-binary-tree-inorder-traversal-python&golang实现

输入:root = [1,null,2]
输出:[1,2]

提示:

树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal

python

# 0094.二叉树中序遍历
# 递归 & 迭代

class Solution:
    def inOrderRecur(self, head: TreeNode) -> int:
        """
        递归遍历,LNR, 左根右
        :param head:
        :return:
        """
        def traversal(head):
            # 递归终止条件
            if head == None:
                return
            traversal(head.left)
            print(head.val + " ")
            res.append(head.val)
            traversal(head.right)
        res = []
        traversal(head)
        return res

    def inorderItration(self, head: TreeNode):
        """
        迭代遍历,LNR, 左根右
        :param head:
        :return:
        """
        if head == None:
            return

        cur = head
        stack = []
        res = []
        while cur or stack:
            # 先迭代访问最底层的左子树节点
            if cur:
                stack.append(cur)
                cur = cur.left
            # 到达最左节点后处理栈顶节点
            else:
                cur = stack.pop()
                res.append(cur.val)
                # 取栈顶元素的右节点
                cur = cur.right
        return res

golang

package main

import "container/list"

// 二叉树的中序遍历 -> 递归 && 迭代
// 递归遍历
func InOrderTraversal(root *TreeNode) []int {
	// 递归遍历, LNR, 左根右
	var res = []int{}
	var inorder func(node *TreeNode)
	inorder = func(node *TreeNode) {
		if node == nil {
			return
		}
		inorder(node.Left)
		res = append(res, node.Val)
		inorder(node.Right)
	}
	inorder(root)
	return res
}

// 迭代遍历 LNR 左中右 左根右
func InOrder(root *TreeNode) []int {
	var res = []int{}
	if root == nil {
		return nil
	}
	stack := list.New() // 创建链表容器
	node := root

	// 1.先将所有的左节点找到,压入栈中
	for node != nil {
		stack.PushBack(node)
		node = node.Left
	}
	// 2.对栈中的每个节点先弹出加入到res中,再找到该节点的右节点的所有左节点加入栈中
	for stack.Len() > 0 {
		e := stack.Back()
		node := e.Value.(*TreeNode)
		stack.Remove(e)
		// 找到该节点的右节点,再搜索其所有的左节点加入栈中
		res = append(res, node.Val)
		node = node.Right
		for node != nil {
			stack.PushBack(node)
			node = node.Left
		}
	}
	return res
}

上一篇:Python二分法查找


下一篇:PAT (Advanced Level) Practice 1151 LCA in a Binary Tree (30 分) 凌宸1642