226. Invert Binary Tree
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
//树的结点定义
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
递归算法:
对于每个节点,交换左右子树,然后递归左右子树,这样就实现了数的反转:
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
// 需要保存此时的左侧结点,
TreeNode left = root.left;
root.left = invertTree(root.right);
root.right = invertTree(left);
return root;
}
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.right);
invertTree(root.left);
return root;
}
采用广度优先遍历的方法,使用队列实现。二叉树的遍历
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
Queue<TreeNode> q = new LinkedList<>();
//加入根节点
q.offer(root);
while (!q.isEmpty()) {
TreeNode temp = q.poll();
TreeNode cur = temp.left;
temp.left = temp.right;
temp.right = cur;
if (temp.left != null)
q.offer(temp.left);
if (temp.right != null)
q.offer(temp.right);
}
return root;
}