/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
rec(root);
}
public TreeNode rec(TreeNode root) {
if (root==null) return root;
TreeNode leftsub = rec(root.left);
TreeNode rightsub = rec(root.right);
root.left = null;
root.right = leftsub;
TreeNode rightmost = leftsub;
if(rightmost!=null) {
while (rightmost.right!=null) {
rightmost = rightmost.right;
}
}
if (rightmost!=null) rightmost.right = rightsub;
else root.right = rightsub;
return root;
}
}
没有评论:
发表评论