二叉树前序非递归遍历

package tree

type Node struct {
	Val   int
	Left  *Node
	Right *Node
}

func NewNode(val int) *Node {
	node := &Node{
		Val:   val,
		Left:  nil,
		Right: nil,
	}
	return node
}

前序遍历:

package main

import (
	tree "awesomeProject/interview/Tree"
	"fmt"
)

//非递归前序遍历(root->left->right)
func preorderTraversal(root *tree.Node) []int {
	result := make([]int, 0)
	//首先判断root节点
	if root == nil {
		return result
	}
	//创建一个栈,存储树节点
	stack := make([]*tree.Node, 0)

	//根节点不为空或者还有节点需要从栈中弹出
	for root != nil || len(stack) != 0 {
		//遍历
		for root != nil {
			//前序遍历,先保存根节点
			result = append(result, root.Val)
			//根节点入栈
			stack = append(stack, root)
			//再根节点
			root = root.Left
		}
		//从尾部弹出pop
		node := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		//右子树
		root = node.Right
	}
	return result
}
func main() {
	root := tree.NewNode(1)
	left1 := tree.NewNode(2)
	right1 := tree.NewNode(3)
	root.Left = left1
	root.Right = right1

	left2 := tree.NewNode(4)
	right2 := tree.NewNode(5)
	left1.Left = left2
	left1.Right = right2

	left3 := tree.NewNode(6)
	right3 := tree.NewNode(7)

	right1.Left = left3
	right1.Right = right3

	fmt.Println(preorderTraversal(root)) //[1 2 4 5 3 6 7]
}

 

上一篇:LinkedList底层链表结构


下一篇:LinkedList源码分析(四)