|
給定一顆葉值序列為 (6, 7, 4, 9, 8) 的樹(shù)。
如果有兩顆二叉樹(shù)的葉值序列是相同,那么我們就認(rèn)為它們是葉相似的。
如果給定的兩個(gè)頭結(jié)點(diǎn)分別為 root1 和 root2 的樹(shù)是葉相似的,則返回 true;否則返回 false。
創(chuàng)建二叉樹(shù),遍歷葉子結(jié)點(diǎn),比較根結(jié)點(diǎn)是否相同
代碼:
class Tree{
private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private static List<Node> nodeList = null;
private static class Node {
Node leftChild;
Node rightChild;
int data;
Node(int newData) {
leftChild = null;
rightChild = null;
data = newData;
}
}
public void createBinTree() {
nodeList = new LinkedList<Node>();
// 將一個(gè)數(shù)組的值依次轉(zhuǎn)換為Node節(jié)點(diǎn)
for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex ) {
nodeList.add(new Node(array[nodeIndex]));
}
// 對(duì)前l(fā)astParentIndex-1個(gè)父節(jié)點(diǎn)按照父節(jié)點(diǎn)與孩子節(jié)點(diǎn)的數(shù)字關(guān)系建立二叉樹(shù)
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex ) {
// 左孩子
nodeList.get(parentIndex).leftChild = nodeList
.get(parentIndex * 2 1);
// 右孩子
nodeList.get(parentIndex).rightChild = nodeList
.get(parentIndex * 2 2);
}
// 最后一個(gè)父節(jié)點(diǎn):因?yàn)樽詈笠粋€(gè)父節(jié)點(diǎn)可能沒(méi)有右孩子,所以單獨(dú)拿出來(lái)處理
int lastParentIndex = array.length / 2 - 1;
// 左孩子
nodeList.get(lastParentIndex).leftChild = nodeList
.get(lastParentIndex * 2 1);
// 右孩子,如果數(shù)組的長(zhǎng)度為奇數(shù)才建立右孩子
if (array.length % 2 == 1) {
nodeList.get(lastParentIndex).rightChild = nodeList
.get(lastParentIndex * 2 2);
}
}
/**
* 先序遍歷
*/
public static void preOrderTraverse(Node node) {
if (node == null)
return;
System.out.print(node.data " ");
preOrderTraverse(node.leftChild);
preOrderTraverse(node.rightChild);
}
/**
* 中序遍歷
*/
public static void inOrderTraverse(Node node) {
if (node == null)
return;
inOrderTraverse(node.leftChild);
System.out.print(node.data " ");
inOrderTraverse(node.rightChild);
}
/**
* 后序遍歷
* 將葉子結(jié)點(diǎn)全部存放在一個(gè)List中
*/
static List<Integer> l = new ArrayList<>();
public static List<Integer> postOrderTraverse(Node node) {
if (node == null)
return null;
postOrderTraverse(node.leftChild);
postOrderTraverse(node.rightChild);
// System.out.print(node.data " ");
if (node.leftChild==null && node.rightChild==null){
l.add(node.data);
}
return l;
}
/**
* 判斷兩個(gè)樹(shù)的根結(jié)點(diǎn)知否相等
*/
public static boolean leafSimilar(Node root1, Node root2) {
if(root1.data == root2.data){
List l1 = postOrderTraverse(root1);
List l2 = postOrderTraverse(root2);
if (l1 == l2)
return true;
else
return false;
}else {
return false;
}
}
}
來(lái)源:https://www./content-4-448651.html
|