有关树的测试程序和算法测试类

This commit is contained in:
Yucheng Hu 2018-12-17 00:04:57 -05:00
parent e0ee898920
commit 2d93b0f795
2 changed files with 140 additions and 0 deletions

View File

@ -0,0 +1,55 @@
package com.ossez.lang.tutorial.utils;
import java.util.ArrayList;
import com.ossez.lang.tutorial.models.TreeNode;
/**
*
* @author YuCheng
*
*/
public class TreeUtils {
public static TreeNode initTree(String data) {
// NULL CHECK
if (data.equals("{}")) {
return null;
}
ArrayList<TreeNode> treeList = new ArrayList<TreeNode>();
data = data.replace("{", "");
data = data.replace("}", "");
String[] vals = data.split(",");
// INSERT ROOT
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
treeList.add(root);
int index = 0;
boolean isLeftChild = true;
for (int i = 1; i < vals.length; i++) {
if (!vals[i].equals("#")) {
TreeNode node = new TreeNode(Integer.parseInt(vals[i]));
if (isLeftChild) {
treeList.get(index).left = node;
} else {
treeList.get(index).right = node;
}
treeList.add(node);
}
// LEVEL
if (!isLeftChild) {
index++;
}
// MOVE TO RIGHT OR NEXT LEVEL
isLeftChild = !isLeftChild;
}
return root;
}
}

View File

@ -0,0 +1,85 @@
package com.ossez.lang.tutorial.tests;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ossez.lang.tutorial.models.TreeNode;
import com.ossez.lang.tutorial.utils.TreeUtils;
/**
*
* @author YuCheng
*
*/
public class TreeTest {
private final static Logger logger = LoggerFactory.getLogger(TreeTest.class);
private static List<Integer> loopList = new ArrayList<Integer>();
@Test
public void testMain() {
logger.debug("TREE TEST");
String data = "{1,2,3,4,5,#,6,#,#,7,8,#,#}";
TreeNode treeNode = TreeUtils.initTree(data);
// PRE
loopList = new ArrayList<Integer>();
preOrderTraverselRecursion(treeNode);
System.out.println(loopList);
// IN
loopList = new ArrayList<Integer>();
inOrderTraverselRecursion(treeNode);
System.out.println(loopList);
// POST
loopList = new ArrayList<Integer>();
postOrderTraversalRecursion(treeNode);
System.out.println(loopList);
}
/**
*
* @param root
*/
public void preOrderTraverselRecursion(TreeNode root) {
if (root != null) {
loopList.add(root.val);
preOrderTraverselRecursion(root.left);
preOrderTraverselRecursion(root.right);
}
}
/**
*
* @param root
*/
public void inOrderTraverselRecursion(TreeNode root) {
if (root != null) {
inOrderTraverselRecursion(root.left);
loopList.add(root.val);
inOrderTraverselRecursion(root.right);
}
}
/**
*
* @param root
*/
public void postOrderTraversalRecursion(TreeNode root) {
if (root != null) {
postOrderTraversalRecursion(root.left);
postOrderTraversalRecursion(root.right);
loopList.add(root.val);
}
}
}