/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type Stack struct {
Parr [1000]*TreeNode
Index int
}
func(s *Stack) IsEmpty() bool {
if s.Index <= 0 {
return true
}else {
return false
}
}
func(s *Stack) Push(p *TreeNode) {
s.Parr[s.Index] = p
s.Index = s.Index + 1
}
func(s *Stack) Pop() (*TreeNode){
if s.Index > 0 {
s.Index = s.Index - 1
return s.Parr[s.Index]
}else {
return nil
}
}
func preorderTraversal(root *TreeNode) []int {
rsp := make([]int, 0)
if nil == root {
return rsp
}
stack := Stack{}
stack.Push(root)
for ; !stack.IsEmpty(); {
temp := stack.Pop()
rsp = append(rsp, temp.Val)
if temp.Right != nil {
stack.Push(temp.Right)
}
if temp.Left != nil {
stack.Push(temp.Left)
}
}
return rsp
}
二叉树前序遍历迭代实现
最新推荐文章于 2022-06-21 14:58:43 发布