题目
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.
答案
刚开始没看懂题目什么意思,怎么flip??
看着题目的例子找下规律就懂了
class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if(root == null) return null;
TreeNode ret = recur(root, null);
return ret;
}
public TreeNode recur(TreeNode root, TreeNode parent) {
TreeNode ret;
if(root.left == null && root.right == null) ret = root;
else ret = recur(root.left, root);
root.right = parent;
if(parent != null) {
root.left = parent.right;
parent.left = null;
parent.right = null;
}
return ret;
}
}