zoukankan      html  css  js  c++  java
  • [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
        }
    }
    
  • 相关阅读:
    云计算的三种服务模式:IaaS, PaaS, SaaS
    Docker 容器备份例子
    软件版本号
    git 命令小总结
    【Oracle】ORA-12560: TNS: 协议适配器错误
    【VMware】The VMX process exited permaturely
    Linux(CentOS)安装SQL Server
    Linux源码编译安装httpd
    Linux安装MySQL
    Linux安装Tomcat
  • 原文地址:https://www.cnblogs.com/zhongju/p/13877887.html
Copyright © 2011-2022 走看看