题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/566f7f9d68c24691aa5abd8abefa798c
package main
import (
"fmt"
"os"
"bufio"
"strconv"
"strings"
)
type TreeNode1 struct {
left *TreeNode1
right *TreeNode1
val int
}
func buildTree(sc *bufio.Scanner) *TreeNode1{
sc.Scan()
str := sc.Text()
strArr := strings.Split(str, " ")
father, _ := strconv.Atoi(strArr[0])
left, _ := strconv.Atoi(strArr[1])
right, _ := strconv.Atoi(strArr[2])
root := &TreeNode1{val: father}
if left != 0 {
root.left = buildTree(sc)
}
if right != 0 {
root.right = buildTree(sc)
}
return root
}
func main() {
input := bufio.NewScanner(os.Stdin)
input.Scan()
root := buildTree(input)
prefix(root);
fmt.Printf("\n");
infix(root);
fmt.Printf("\n");
postfix(root);
fmt.Printf("\n");
}
func prefix(node *TreeNode1){
if node == nil {
return
}
fmt.Printf("%d ", node.val)
if node.left != nil {
prefix(node.left)
}
if node.right != nil {
prefix(node.right)
}
return
}
func infix(root *TreeNode1){
if root == nil {
return
}
if root.left != nil {
infix(root.left)
}
fmt.Printf("%d ", root.val)
if root.right != nil {
infix(root.right)
}
return
}
func postfix(root *TreeNode1){
if root == nil {
return
}
if root.left != nil {
postfix(root.left)
}
if root.right != nil {
postfix(root.right)
}
fmt.Printf("%d ", root.val)
return
}
import (
"fmt"
"os"
"bufio"
"strconv"
"strings"
)
type TreeNode1 struct {
left *TreeNode1
right *TreeNode1
val int
}
func buildTree(sc *bufio.Scanner) *TreeNode1{
sc.Scan()
str := sc.Text()
strArr := strings.Split(str, " ")
father, _ := strconv.Atoi(strArr[0])
left, _ := strconv.Atoi(strArr[1])
right, _ := strconv.Atoi(strArr[2])
root := &TreeNode1{val: father}
if left != 0 {
root.left = buildTree(sc)
}
if right != 0 {
root.right = buildTree(sc)
}
return root
}
func main() {
input := bufio.NewScanner(os.Stdin)
input.Scan()
root := buildTree(input)
prefix(root);
fmt.Printf("\n");
infix(root);
fmt.Printf("\n");
postfix(root);
fmt.Printf("\n");
}
func prefix(node *TreeNode1){
if node == nil {
return
}
fmt.Printf("%d ", node.val)
if node.left != nil {
prefix(node.left)
}
if node.right != nil {
prefix(node.right)
}
return
}
func infix(root *TreeNode1){
if root == nil {
return
}
if root.left != nil {
infix(root.left)
}
fmt.Printf("%d ", root.val)
if root.right != nil {
infix(root.right)
}
return
}
func postfix(root *TreeNode1){
if root == nil {
return
}
if root.left != nil {
postfix(root.left)
}
if root.right != nil {
postfix(root.right)
}
fmt.Printf("%d ", root.val)
return
}