“Preorder Traversal Golang” Kode Jawaban

Preorder Traversal Golang

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

func preOrderTraverse(root *TreeNode) int[] {
  list := []int {}
  if root == nil {
    return list
  }
  
  stack := []*TreeNode { root }
  for len(stack) > 0 {
    root = stack[len(stack) - 1]
    stack = stack[0:len(stack) - 1]
    list = append(list, root.Val)

    if root.Left != nil {
      stack = append(stack, root.Left)
    }
    
    if root.Right != nil {
      stack = append(stack, root.Right)
    }
  }
  
  return list
}
Ibrahim Albarghouthi

Inorder Traversal Golang

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

func inOrderTraverse(root *TreeNode) int[] {
  list := []int {}
  if root == nil {
    return list
  }
  
  stack := []*TreeNode { }
  for root != nil || len(stack) > 0 {
    
    for root != nil {
      stack = append(stack, root)
      root = root.Left
    }
    
    root = stack[len(stack) - 1]
    stack = stack[0:len(stack) - 1]
    list = append(list, root.Val)
    root = root.Right
  }
  
  return list
}

Ibrahim Albarghouthi

Jawaban yang mirip dengan “Preorder Traversal Golang”

Pertanyaan yang mirip dengan “Preorder Traversal Golang”

Lebih banyak jawaban terkait untuk “Preorder Traversal Golang” di Go

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya