go实现二叉树任意节点距离

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())
}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值