首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

递归兑现两个二叉树的比较

2012-11-20 
递归实现两个二叉树的比较废话不说,上代码package com.alan.basicimport com.alan.basic.Tree.Node/** *

递归实现两个二叉树的比较
废话不说,上代码

package com.alan.basic;import com.alan.basic.Tree.Node;/** * 二插树 *  * @author alan *  */class Tree {Node root;public Tree() {root = null;}public static class Node {int value;Node left;Node right;public Node(int nvalue) {value = nvalue;left = null;right = null;}}public void insert(int data) {root = insert(root, data);}private Node insert(Node node, int data) {if (node == null) {node = new Node(data);} else {if (data <= node.value) {node.left = insert(node.left, data);}else {node.right = insert(node.right, data);}}return (node); // in any case, return the new pointer to the caller}public void buildTree(int[] data) {for (int i = 0; i < data.length; i++) {insert(data[i]);}}}public class TreeCompare {public static void main(String[] args) {Tree t1 = new Tree();Tree t2 = new Tree();int[] data1 = { 1, 2, 3 };int[] data2 = { 1, 2, 3 };t1.buildTree(data1);t2.buildTree(data2);System.out.print(compare(t1.root, t2.root));}/** *递归比较两个树是否完全相同 * @param tn1 * @param tn2 * @return */private static boolean compare(Node tn1, Node tn2) {if (tn1 == null || tn2 == null) {if (tn1 == null && tn2 == null) {return true;} else {return false;}}if (tn1.value == tn2.value) {return (compare(tn1.left, tn2.left) && compare(tn1.right, tn2.right));}return false;}}


热点排行