leetcode刷题笔记一百四十四题与一百四十五题 二叉树的前序遍历与后序遍历
leetcode刷题笔记一百四十四题与一百四十五题 二叉树的前序遍历与后序遍历
源地址:
问题描述:
144题问题描述
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?145题问题描述
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
//144 与 145 均可使用迭代(借助栈) 或者递归方法
//递归方法较为简单,按照顺序需要,向List中添加节点值
//迭代方法需要使用栈结果辅助
//前序遍历为中左右,先访问根节点,而后先压入右子树,再压入左子树
//后序遍历为左右中,可通过按中右左顺序访问,后颠倒即可
//144
//递归
/**
* 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 preorderTraversal(root: TreeNode): List[Int] = {
var res = mutable.ListBuffer[Int]()
def helper(root: TreeNode): Unit = {
if (root == null) return
res += root.value
//println(res.mkString)
if (root.left != null) helper(root.left)
if (root.right != null) helper(root.right)
}
helper(root)
return res.toList
}
}
//迭代
/**
* 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 preorderTraversal(root: TreeNode): List[Int] = {
var res = mutable.ListBuffer[Int]()
var stack = mutable.Stack[TreeNode]()
if (root != null) stack.push(root)
while (stack.isEmpty == false) {
val node = stack.pop()
if (node != null) {
res += node.value
stack.push(node.right)
stack.push(node.left)
}
}
return res.toList
}
}
//145
//递归
/**
* 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 postorderTraversal(root: TreeNode): List[Int] = {
var res = mutable.ListBuffer[Int]()
def helper(root: TreeNode): Unit = {
if (root == null) return
if (root.left != null) helper(root.left)
if (root.right != null) helper(root.right)
res += root.value
}
helper(root)
return res.toList
}
}
//迭代
/**
* 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 postorderTraversal(root: TreeNode): List[Int] = {
var res = mutable.ListBuffer[Int]()
var stack = mutable.Stack[TreeNode]()
if (root != null) stack.push(root)
while (stack.isEmpty == false){
val node = stack.pop()
if (node != null) res += node.value
if (node.left != null) stack.push(node.left)
if (node.right != null) stack.push(node.right)
}
return res.reverse.toList
}
}