二叉树翻转
在这里插入图片描述

树的初始化可以粗暴一些。
如果要看一棵比较简单的树的结构,可以用json包序列化打印出来看

非递归实现

package main

import (
	"encoding/json"
	"fmt"
	"github.com/eapache/queue"
)

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

func (n *Node) Mirror() {
	q := queue.New()
	q.Add(n)

	for {
		if q.Length() <= 0 {
			break
		}
		node := q.Remove().(*Node)
		if node == nil {
			break
		}

		tmp := node.Left
		node.Left = node.Right
		node.Right = tmp

		if node.Left != nil {
			q.Add(node.Left)
		}

		if node.Right != nil {
			q.Add(node.Right)
		}

	}
}

func main() {
	root := &Node{Key: 4}

	root.Left = &Node{
		Key: 2,
		Left: &Node{
			Key:   1,
			Left:  nil,
			Right: nil,
		},
		Right: &Node{
			Key:   3,
			Left:  nil,
			Right: nil,
		},
	}

	root.Right = &Node{
		Key: 7,
		Left: &Node{
			Key:   6,
			Left:  nil,
			Right: nil,
		},
		Right: &Node{
			Key:   9,
			Left:  nil,
			Right: nil,
		},
	}
	root.Mirror()
	out, _ := json.MarshalIndent(root, "", "    ")
	fmt.Println(string(out))


}


输出

{
    "Key": 4,
    "Left": {
        "Key": 7,
        "Left": {
            "Key": 9,
            "Left": null,
            "Right": null
        },
        "Right": {
            "Key": 6,
            "Left": null,
            "Right": null
        }
    },
    "Right": {
        "Key": 2,
        "Left": {
            "Key": 3,
            "Left": null,
            "Right": null
        },
        "Right": {
            "Key": 1,
            "Left": null,
            "Right": null
        }
    }
}

递归实现

package main

import (
	"encoding/json"
	"fmt"
)

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

func (n *Node) Mirror2() {
	tmp := n.Left
	n.Left = n.Right
	n.Right = tmp

	if n.Left != nil {
		n.Left.Mirror2()
	}
	if n.Right != nil {
		n.Right.Mirror2()
	}
}

func main() {
	root := &Node{Key: 4}

	root.Left = &Node{
		Key: 2,
		Left: &Node{
			Key:   1,
			Left:  nil,
			Right: nil,
		},
		Right: &Node{
			Key:   3,
			Left:  nil,
			Right: nil,
		},
	}

	root.Right = &Node{
		Key: 7,
		Left: &Node{
			Key:   6,
			Left:  nil,
			Right: nil,
		},
		Right: &Node{
			Key:   9,
			Left:  nil,
			Right: nil,
		},
	}
	root.Mirror2()
	out, _ := json.MarshalIndent(root, "", "    ")
	fmt.Println(string(out))
}

输出

{
    "Key": 4,
    "Left": {
        "Key": 7,
        "Left": {
            "Key": 9,
            "Left": null,
            "Right": null
        },
        "Right": {
            "Key": 6,
            "Left": null,
            "Right": null
        }
    },
    "Right": {
        "Key": 2,
        "Left": {
            "Key": 3,
            "Left": null,
            "Right": null
        },
        "Right": {
            "Key": 1,
            "Left": null,
            "Right": null
        }
    }
}