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
        }
    }
    
  • 相关阅读:
    PID控制心得 2013/2/11
    在LaTeX文档中插入图片的几种常用的方法
    学习总结 2013/2/11
    eclipse 中引用其他项目及项目打包
    随笔2013/2/13
    随笔2013/2/19
    【转载】Latex对中文的支持 模版
    Latex 第二个程序
    Fences 桌面图标整理收纳箱
    消除“星期一综合症” 大前研一的周末时间分配术
  • 原文地址:https://www.cnblogs.com/zhongju/p/13877887.html
Copyright © 2011-2022 走看看