226. Invert Binary Tree
Recursive
The structure of recursive solution code looks like a recursive pre-order DFS.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
// swap the address of left tree and right tree of the current node
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
// the recursively call of the left tree
invertTree(root.left);
// the recursively call of the right tree
invertTree(root.right);
return root;
}
}
Iterative
The structure of Iterative solution code looks like a BFS.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.addFirst(root);
while (!queue.isEmpty()) {
TreeNode x = queue.removeFirst();
// swap the address of left tree and right tree of the current node
TreeNode temp = x.left;
x.left = x.right;
x.right = temp;
if (x.left != null) {
queue.addLast(x.left);
}
if (x.right != null) {
queue.addLast(x.right);
}
}
return root;
}
}