leetcode刷题笔记九十四题 二叉树的中序遍历

leetcode刷题笔记九十四题 二叉树的中序遍历

源地址:94. 二叉树的中序遍历

问题描述:

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

示例:

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

2
/
3

输出: [1,3,2]

/**
本题共有三种解法,第一种为常规的递归解法
*/
/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
import scala.collection.mutable
object Solution {
    def inorderTraversal(root: TreeNode): List[Int] = {
        def helper(root: TreeNode, res: mutable.ListBuffer[Int]): Unit = {
            if (root != null){
                if(root.left != null)   helper(root.left, res)
                res += root.value
                if(root.right != null) helper(root.right, res)
            }
        }
        var res = new mutable.ListBuffer[Int]()
        helper(root, res)
        return res.toList
    }
}

/**
非递归模式,使用Stack辅助的解法,沿左子树入栈,直至左子树为空,开始退栈,并访问退栈元素的右子树
*/
/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
import scala.collection.mutable
object Solution {
    def inorderTraversal(root: TreeNode): List[Int] = {
        var res = mutable.ListBuffer[Int]()
        var stack = mutable.Stack[TreeNode]()
        var start = root

        while (stack.size > 0 || start != null){
            if (start != null){
                stack.push(start)
                start = start.left
            }
            else{
                val temp = stack.pop()
                res += temp.value
                start = temp.right
            }
        }
        return res.toList      
    }
}

/**
不借用额外空间结构辅助莫里斯遍历,依次将以root为根的右子树移至root左子树的最右节点的右儿子
*/
/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
import scala.collection.mutable
object Solution {
    def inorderTraversal(root: TreeNode): List[Int] = {
        var res = mutable.ListBuffer[Int]()
        var stack = mutable.Stack[TreeNode]()
        var start = root
        var prev = root

        while (start != null){
            //左子树不为空
            if(start.left != null){
                prev = start.left
                while(prev.right != null){
                    prev = prev.right
                }
                prev.right = start
                var temp = start
                start = start.left
                temp.left = null
            }
            //左子树为空
            else{
                res += start.value
                start = start.right
            }
        }
        return res.toList      
    }
}
posted @ 2020-07-30 18:56  ganshuoos  阅读(111)  评论(0编辑  收藏  举报