问题描述
思路
java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
helper(root);
}
private TreeNode helper(TreeNode root){
if (root==null)
return null;
//分
TreeNode leftLast=helper(root.left);
TreeNode rightLast=helper(root.right);
//和
if(leftLast!=null){
leftLast.right=root.right;//根的右结点连在左结点下
root.right=root.left;//根的左结点连在右结点下
root.left=null;//左边置空
}
if(rightLast!=null)
return rightLast;//如果rightLast存在返回rightLast
if(leftLast!=null)
return leftLast;//如果leftLast存在返回leftLast
return root;//leftLast和rightLast都为空
}
}