ideas
Recursive questions are interesting
Recursion: swap left and right nodes
Exit condition: current node is null
topic
Take a binary tree and transform it into its mirror image.
Sample
Input tree:
8
/
6 10
/ \ /
5 7 9 11
[8,6,10,5,7,9,11,null,null,null,null,null,null,null,null]
Output tree:
8
/
10 6
/ \ /
11 9 7 5
[8,10,6,11,9,7,5, null, null, null, null, null, null, null, null]
java code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private void swap(TreeNode r) {
TreeNode tmp = r.left;
r.left = r.right;
r.right = tmp;
}
public void mirror(TreeNode root) {
if (root == null) return;
mirror(root.left);
mirror(root.right);
swap(root);
}
}