package main
import (
"container/list"
"fmt"
)
// Binary Tree
type BinaryTree struct {
Data interface{}
Left *BinaryTree
Right *BinaryTree
}
// 初始化二叉树
func NewBinaryTree(data interface{}) *BinaryTree {
return &BinaryTree{Data: data}
}
//获得节点路径
func getNodePath(pRoot *BinaryTree, pNode int, l *list.List ) bool {
var found bool = false
l.PushBack(pRoot)
i := (pRoot.Data).(int)
if i == pNode {
return true
}
if !found && pRoot.Left != nil {
getNodePath(pRoot.Left, pNode, l)
}
if !found && pRoot.Right != nil {
getNodePath(pRoot.Right, pNode, l)
}
if !found {
l.Remove(l.Back())
}
return found
}
//获得最近相同根节点的值
func getLastCommonNode(path1 *list.List, path2 *list.List) int{
var pLast *BinaryTree
firstEle1 := path1.Front()
firstEle2 := path2.Front()
for firstEle1 != path1.Back() && firstEle2 != path2.Back() {
if firstEle1.Next() == firstEle2.Next(){
pLast = firstEle1.Next().Value.(*BinaryTree)
}
firstEle1 = firstEle1.Next()
firstEle2 = firstEle2.Next()
}
return pLast.Data.(int)
}
func main() {
t := NewBinaryTree(1)
t.Left = NewBinaryTree(3)
t.Right = NewBinaryTree(6)
t.Left.Left = NewBinaryTree(4)
t.Left.Right = NewBinaryTree(5)
t.Left.Left.Left = NewBinaryTree(7)
fmt.Println(t)
path1 := list.New();
path2 := list.New();
path3 := list.New();
s1 := 3
s2 := 7
getNodePath(t, s1, path1)
getNodePath(t, s2, path2)
common := getLastCommonNode(path1, path2)
getNodePath(t,common,path3)
distance := path1.Len() + path2.Len() - 2*path3.Len()
fmt.Println(distance)
//fmt.Println(t.PreOrderNoRecursion())
//fmt.Println(t.InOrderNoRecursion())
//fmt.Println(t.PostOrderNoRecursion())
}