leetcode没有这个题目,自己写了一个测试程序
含自己的解决算法
import java.util.List;
import java.util.Random;
public class TreeNextNodeTest {
public static void main(String[] args) {
//根据前中后序生成树
MyTree root = MyTree.getTreeWithPostMid("DCBHKGFEA".toCharArray(),
"BDCAEHGKF".toCharArray());
MyTree sample = getTestSample(root);
System.out.println("Your method: " + solve(sample));
System.out.println("Correct Answer: " + getAns(sample));
System.out.println("Current Node Value" + sample.getVal());
System.out.println(root.getTraversal(TraversalMethod.MID));
}
//随机数获取测试数据
private static MyTree getTestSample(MyTree root){
int depth = root.getDepth();
Random random = new Random(System.currentTimeMillis());
int randomDepth = random.nextInt(depth);
MyTree ans = root;
while (ans != null && randomDepth > 0){
randomDepth--;
int swt = random.nextInt(10)/5;
if (swt == 0 && ans.getLeft() != null){
ans = ans.getLeft();
} else if (ans.getRight() != null) {
ans = ans.getRight();
}
}
return ans;
}
//获取正确答案
private static Character getAns(MyTree current){
MyTree father = current;
while (father.getFather() != null){
father = father.getFather();
}
List<Character> list = father.getTraversal(TraversalMethod.MID);
try{
Character c = new Character(list.get(list.indexOf(current.getVal()) + 1 ));
return c;
} catch (Exception e){
}
return null;
}
//自己的方法
public static Character solve(MyTree current){
if (current.getRight() != null){
return getTheLeft(current.getRight());
} else if (current == current.getFather().getLeft()){
return current.getFather().getVal();
} else {
MyTree child = current;
MyTree father = current.getFather();
while (father != null && child != father.getLeft()){
child = father;
father = child.getFather();
}
return (father == null) ? null : father.getVal();
}
}
private static Character getTheLeft(MyTree current){
MyTree ans = current;
while (ans.getLeft() != null){
ans = ans.getLeft();
}
return ans.getVal();
}
}