public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
// 使用分治法解决问题
public void flatten(TreeNode root) {
if (root == null) return;
flatten(root.left); // flatten 左子树
flatten(root.right); // flatten 右子树
if (root.left == null) return;
TreeNode leftLowest = root.left;
while (leftLowest.right != null) {
leftLowest = leftLowest.right;
}
leftLowest.right = root.right;
root.right = root.left;
root.left = null;
}
} class Solution:
"""
@param: root: a TreeNode, the root of the binary tree
@return:
"""
def flatten(self, root):
def helper(root):
if not root.left and not root.right:
return root
if not root.left:
right = helper(root.right)
return right
if not root.right:
left = helper(root.left)
root.right = root.left
root.left = None
return left
else:
left = helper(root.left)
right = helper(root.right)
left.right = root.right
root.right = root.left
root.left = None
return right
if root is None:
return root
helper(root)
return root