我已经附上了两棵树进行测试,但下面的答案很奇怪。 输入是两棵树并检查它们是否是倒置版本。所以我写了一个反转函数和一个BFS遍历来将树节点存储到一个字符串中,通过比较两个字符串来检查它们是否是反转版本。
第一棵树是 五 15 14 9 6 3 1 第二棵树是: 五 15 14 9 6 3 1 五 14 15 3 6 9 1 不,不是镜子想象
处理完成,退出代码为0
public class CheckMirrorTree {
public static void main(String[] args) {
// add the first tree
TreeNode root = new TreeNode(5);
root.left = new TreeNode(15);
root.right = new TreeNode(14);
TreeNode rightChild = root.right;
TreeNode leftChild = root.left;
rightChild.left = new TreeNode(3);
rightChild.left.right = new TreeNode(1);
leftChild.right = new TreeNode(6);
leftChild.left = new TreeNode(9);
System.out.println("The first tree is");
String root1 = traverse(root);
// add the second tree
System.out.println("The second tree is:");
TreeNode secondRoot = new TreeNode(5);
secondRoot.right = new TreeNode(15);
secondRoot.left = new TreeNode(14);
TreeNode secondRightChild = secondRoot.right;
TreeNode secondLeftChild = secondRoot.left;
secondRightChild.left = new TreeNode(6);
secondRightChild.right = new TreeNode(9);
secondLeftChild.right = new TreeNode(3);
secondLeftChild.right.left = new TreeNode(1);
String root2 = traverse(secondRoot);
if (root1 == root2){
System.out.println("Yes, mirror images");
}else {
System.out.println("No, not mirror imagines");
}
}
static Deque<TreeNode> queue = new ArrayDeque();
static List<Integer> result = new LinkedList();
static Deque<TreeNode> invertQueue = new ArrayDeque();
static private TreeNode invertTree(TreeNode root) {
invertQueue.add(root);
TreeNode reserve = root;
while (!invertQueue.isEmpty()) {
if (root.left != null || root.right != null) {
invertQueue.poll();
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
if (root.left != null)
invertQueue.add(root.left);
if (root.right != null)
invertQueue.add(root.right);
}
root = invertQueue.poll();
}
return reserve;
}
static private String traverse (TreeNode root){ // Each child of a tree is a root of its subtree.
queue.add(root);
helper(root);
// print out the tree
String res = "";
for (int i : result) {
System.out.println(i);
res += i;
}
return res;
}
static private void helper(TreeNode root) {
while (!queue.isEmpty()) {
if(root.left != null || root.right != null) {
TreeNode temp = queue.poll();
result.add(temp.val);
if (root.left != null)
queue.add(root.left);
if (root.right != null)
queue.add(root.right);
helper(queue.peek());
}
// deal with the ending nodes
if (root.left == null && root.right == null) {
if (queue.size() == 0) {
result.add(root.val);
return;
}
result.add(queue.poll().val);
root = queue.peek();
}
}
}
}
答案 0 :(得分:0)
root1 == root2
不是你如何检查两个字符串是否相等。尝试:
root1.equals(root2);
然后输入你的if语句并打印一些东西。 由于没有其他内容被打印,我建议发布遍历方法,因为这可能是程序提前退出的地方。