[英]Something wrong with my Invert tree or BFS traverse?
我已经附加了两棵树进行测试,但是下面的答案很奇怪。 输入的是两棵树,并检查它们是否为反向版本。 因此,我通过比较两个字符串以检查它们是否为反向版本,编写了一个反向函数和BFS遍历以将树节点存储为字符串。
第一棵树是5 15 14 9 6 3 1第二棵树是:5 15 14 9 6 3 1 5 14 15 3 6 9 1不,不是镜像想象的
流程结束,退出代码为0
公共类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();
}
}
}
}
root1 == root2
不是您如何检查两个字符串是否相等。 尝试:
root1.equals(root2);
然后,应输入if语句,然后将打印一些内容。 由于没有其他内容可以打印,因此我建议发布遍历方法,因为这可能是程序提前退出的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.