“Golang traversal inorder pohon pencari biner” Kode Jawaban

Golang traversal inorder pohon pencari biner

package main
 
import "fmt"
 
type Node struct {
	val   int
	left  *Node
	right *Node
}
 
func InorderRecursive(root *Node) {
	if root == nil {
		return
	}
 
	InorderRecursive(root.left)
	fmt.Printf("%d ", root.val)
	InorderRecursive(root.right)
}
 
func main() {
	/*
				10
			   /  \
			 20	   30
			/ \      \
		   40  50     60
		  /
		 70
	*/
 
	root := &Node{10, nil, nil}
	root.left = &Node{20, nil, nil}
	root.right = &Node{30, nil, nil}
	root.left.left = &Node{40, nil, nil}
	root.left.right = &Node{50, nil, nil}
	root.right.right = &Node{60, nil, nil}
	root.left.left.left = &Node{70, nil, nil}
 
	fmt.Println("Inorder Traversal - recursive solution : ")
	InorderRecursive(root)
}
Tired Termite

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

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

Jawaban yang mirip dengan “Golang traversal inorder pohon pencari biner”

Pertanyaan yang mirip dengan “Golang traversal inorder pohon pencari biner”

Lebih banyak jawaban terkait untuk “Golang traversal inorder pohon pencari biner” di Go

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya