leetcode刷题笔记一百一十四题 二叉树展开为链表
leetcode刷题笔记一百一十四题 二叉树展开为链表
源地址:114. 二叉树展开为链表
问题描述:
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/
2 5
/ \
3 4 6
将其展开为:1
2
3
4
5
6
/**
本题方法可以使用先序遍历方式,具体可分为递归和迭代
另一种方法可以使用先驱结点
*/
//递归方法 -- 先序遍历 将先序遍历结果放入res,然后修改左右结点
/**
* Definition for a binary tree node.
* class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
* var value: Int = _value
* var left: TreeNode = _left
* var right: TreeNode = _right
* }
*/
import scala.collection.mutable
object Solution {
def flatten(root: TreeNode): Unit = {
var res = new mutable.ListBuffer[TreeNode]()
preOrderTraversal(root)
for (i <- 1 to res.size - 1){
val prev = res(i-1)
val cur = res(i)
prev.left = null
prev.right = cur
}
def preOrderTraversal(root: TreeNode): Unit = {
if (root != null){
res += root
preOrderTraversal(root.left)
preOrderTraversal(root.right)
}
}
}
}
//与递归方法思想一致,使用stack实现迭代方法
/**
* Definition for a binary tree node.
* class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
* var value: Int = _value
* var left: TreeNode = _left
* var right: TreeNode = _right
* }
*/
import scala.collection.mutable
object Solution {
def flatten(root: TreeNode): Unit = {
if (root == null) return
val stack = new mutable.Stack[TreeNode]()
stack.push(root)
var prev: TreeNode = null
while (stack.isEmpty == false){
val cur = stack.pop
if (prev != null){
prev.left = null
prev.right = cur
}
val left = cur.left
val right = cur.right
if (right != null) stack.push(right)
if (left != null) stack.push(left)
prev = cur
}
}
}
//对pre cur next结点调整先序结点位置,本质还是按照先序遍历改变树的结构
/**
* Definition for a binary tree node.
* class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
* var value: Int = _value
* var left: TreeNode = _left
* var right: TreeNode = _right
* }
*/
import scala.collection.mutable
object Solution {
def flatten(root: TreeNode): Unit = {
var cur = root
while (cur != null){
if (cur.left != null){
var next = cur.left
var predecessor = next
while (predecessor.right != null) predecessor = predecessor.right
predecessor.right = cur.right
cur.left = null
cur.right = next
}
cur = cur.right
}
}
}