一. 定义树的的节点
不同二叉树的叶节点上可以保存相同的值序列。例如,以下两个二叉树都保存了序列 1,1,2,3,5,8,13
。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.wedoo.coderyeah.module.iot.algorithm;
import lombok.Data;
@Data public class TreeNode { private TreeNode Left; private Integer Value; private TreeNode Right;
TreeNode(int x) { Value = x; } }
|
二. 具体实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package com.wedoo.coderyeah.module.iot.algorithm;
import java.util.ArrayList; import java.util.List;
public class BinaryTree {
public static void saveNodeValues(TreeNode node, List<Integer> list) { if (node == null) { return; } saveNodeValues(node.getLeft(), list); list.add(node.getValue()); saveNodeValues(node.getRight(), list); }
public static Boolean compare(TreeNode tree1, TreeNode tree2) { List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); saveNodeValues(tree1, list1); saveNodeValues(tree2, list2); System.out.println("list1:" + list1); System.out.println("list2:" + list2); return list1.equals(list2); }
public static void main(String[] args) { TreeNode treeNode = new TreeNode(1); treeNode.setLeft(new TreeNode(2)); treeNode.setRight(new TreeNode(3)); TreeNode treeNode2 = new TreeNode(1); treeNode2.setLeft(new TreeNode(2)); treeNode2.setRight(new TreeNode(9));
Boolean aBoolean = compare(treeNode2, treeNode); System.out.println("aBoolean: " + aBoolean); } }
|
三. GO实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package main
import ( "fmt" "golang.org/x/tour/tree" )
func main() { t1 := tree.New(1) t2 := tree.New(1) b := compare(t1, t2) fmt.Println("t1==t2:", b) }
func Walk(t *tree.Tree, ch chan int) { if t == nil { return } Walk(t.Left, ch) ch <- t.Value Walk(t.Right, ch) }
func compare(t1, t2 *tree.Tree) bool { c1 := make(chan int) c2 := make(chan int) go Walk(t1, c1) go Walk(t2, c2) for i := 0; i < 10; i++ { x, y := <-c1, <-c2 fmt.Println(x, y) if x != y { return false } } return true }
|