Loading

[LeetCode] 94. Binary Tree Inorder Traversal(二叉树的中序遍历)

Description

Given the root of a binary tree, return the inorder traversal of its nodes' values.
给定一个二叉树的树根 root,返回该二叉树的中序遍历值列表

Examples

Example 1

Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2

Input: root = []
Output: []

Example 3

Input: root = [1]
Output: [1]

Example 4

Input: root = [1,2]
Output: [2,1]

Example 5

Input: root = [1,null,2]
Output: [1,2]

Constraints

  • The number of nodes in the tree is in the range [0, 100].

  • -100 <= Node.val <= 100

Follow up

Recursive solution is trivial, could you do it iteratively?

Solution

递归做法是显而易见的,甚至可以直接手撸代码,如下所示:

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    private val result = arrayListOf<Int>()

    fun inorderTraversal(root: TreeNode?): List<Int> {
        inOrder(root)
        return result
    }

    private fun inOrder(root: TreeNode?) {
        if (root != null) {
            inOrder(root.left)
            result.add(root.`val`)
            inOrder(root.right)
        }
    }
}

非递归做法需要用到栈来模拟整个过程,代码如下:

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
import java.util.*

class Solution {
    fun inorderTraversal(root: TreeNode?): List<Int> {
        if (root == null) {
            return emptyList()
        }

        val result = arrayListOf<Int>()
        val stack: Deque<TreeNode> = LinkedList()
        var mRoot = root
        while (stack.isNotEmpty() || mRoot != null) {
            if (mRoot != null) {
                // 等价于 inOrder(root.left)
                stack.push(mRoot)
                mRoot = mRoot.left
            } else {
                mRoot = stack.pop()
                result.add(mRoot.`val`)
                // 等价于 inOrder(root.right)
                mRoot = mRoot?.right
            }
        }
        return result
    }
}
posted @ 2020-10-26 12:49  Zhongju.copy()  阅读(117)  评论(0编辑  收藏  举报