Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Input: [1,2,3,4,5]

1
/ \
2 3
/ \
4 5

Output: return the root of the binary tree [4,5,2,#,#,3,1]

4
/ \
5 2
/ \
3 1

实际上是把整个树🌳顺时针翻转了; 4 2 5的位置看出翻转的操作应该是什么样的.

我觉得还是要见过这种题,不然自己写迭代的那个解法实际上很容易错

1
2
3
4
5
6
7
8
9
10
11
12
13
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null || root.left == null && root.right == null) return root;

TreeNode newRoot = upsideDownBinaryTree(root.left);

root.left.left = root.right;
root.left.right = root;

root.left = null; // just for this time
root.right = null;

return newRoot;
}
  1. rootnull或者是leaf node(root.left == null && root.right == null)的时候,就return;
  2. 每次翻转三角形三个节点的时候,右子节点暂时两个子节点都赋值为null;