《leetcode-go》二叉树遍历

前序、中序、后序遍历

package main
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型一维数组
*/
type Stack struct {
	Val []*TreeNode
	i   int
}

func (stack *Stack) Push(node *TreeNode) {
	stack.Val = append(stack.Val, node)
	stack.i++
}

func (stack *Stack) Pop() (node *TreeNode) {
	node = stack.Val[stack.i-1]
	stack.Val = stack.Val[0 : stack.i-1]
	stack.i--
	return
}
func postorderTraversal( root *TreeNode ) []int {
    // write code here
    var retList []int
	if root == nil {
		return retList
	}
	var pre *TreeNode
	stack := new(Stack)
	stack.Push(root)
	for len(stack.Val) > 0 {
		node := stack.Val[stack.i-1]
		if (pre != nil && (pre == node.Left || pre == node.Right)) || (node.Left == nil && node.Right == nil) {
			//fmt.Println(node.Val)
			retList = append(retList, node.Val)
			stack.Pop()
			pre = node
			continue
		}
		if node.Right != nil {
			stack.Push(node.Right)
		}
		if node.Left != nil {
			stack.Push(node.Left)
		}
	}
	return retList
}

func preorderTraversal( root *TreeNode ) []int {
    // write code here
    var retList []int
	if root == nil {
		return retList
	}
	stack := new(Stack)
	stack.Push(root)
	for len(stack.Val) > 0 {
		node := stack.Pop()
		//fmt.Println(node.Val)
		retList = append(retList, node.Val)
		if node.Right != nil {
			stack.Push(node.Right)
		}
		if node.Left != nil {
			stack.Push(node.Left)
		}
	}
	return retList
}

func inorderTraversal( root *TreeNode ) []int {
    // write code here
    var retList []int
	if root == nil {
		return retList
	}
	stack := new(Stack)
	stack.Push(root)
	node := root
	for len(stack.Val) > 0 {
		for node.Left != nil {
			stack.Push(node.Left)
			node = node.Left
		}
		for len(stack.Val) > 0 {
			node = stack.Pop()
			//fmt.Println(node.Val)
			retList = append(retList, node.Val)
			if node.Right != nil {
				stack.Push(node.Right)
				node = node.Right
				break
			}
		}
	}
	return retList
}

 

你可能感兴趣的:(leetCode-go)