Prompt
Write a function that takes in a Binary Tree and inverts it. In other words, the function should swap every left node in the tree for its corresponding right node.
Each BinaryTree node has an integer value , a left child node, and a right child node. Children nodes can either be BinaryTree nodes themselves or None / null .
Sample Input
Sample Output
Solution
import java.util.*;
class Program {
// O(n) time | O(d) space - where d is the depth of the tree
public static void invertBinaryTree(BinaryTree tree) {
if (tree == null) {
return;
}//A
// BinaryTree node = tree.left;
// tree.left = tree.right;
// tree.right = node;
swapLeftAndRight(tree);
invertBinaryTree(tree.left);
invertBinaryTree(tree.right);
}
public static void swapLeftAndRight(BinaryTree tree) {//A
BinaryTree node = tree.left;
tree.left = tree.right;
tree.right = node;
}
static class BinaryTree {
public int value;
public BinaryTree left;
public BinaryTree right;
public BinaryTree(int value) {
this.value = value;
}
}
}
# 1A
务必每次把swap抽象出来
Solution 2
import java.util.*;
class Program {
public static void invertBinaryTree(BinaryTree tree) {
ArrayDeque<BinaryTree> queue = new ArrayDeque<BinaryTree>();//A
queue.addLast(tree);
while(queue.size() > 0){//A
BinaryTree currentNode = queue.pollFirst();
//if (currentNode == null):{
// if (currentNode == null){
// continue;//C
// }
swapLeftAndRight(currentNode);
if (currentNode.left != null) {//B
queue.addLast(currentNode.left);
}
if (currentNode.right != null) {
queue.addLast(currentNode.right);
}
// queue.addLast(null);
}
}
public static void swapLeftAndRight(BinaryTree tree) {//
BinaryTree node = tree.left;
tree.left = tree.right;
tree.right = node;
}
static class BinaryTree {
public int value;
public BinaryTree left;
public BinaryTree right;
public BinaryTree(int value) {
this.value = value;
}
}
}
# 2A
ArrayDeque的methods
# 2B
Throws: NullPointerException - if the specified element is null