Given a binary tree, flatten it to a linked list in-place.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*遍历方法
class Solution {
private TreeNode lastnode=null;//定义上个节点
public void flatten(TreeNode root) {
if (root==null){
return;
}
if(lastnode!=null){
lastnode.left=null;
lastnode.right=root;//上个节点的右子树变成当前节点
}
lastnode=root;
TreeNode right=lastnode.right;//避免右子树被覆盖
flatten(root.left);
flatten(right);
}
}
*/
//分治法
class Solution {
public void flatten(TreeNode root) {
helper(root);
}
//flatten root and return the last node
private TreeNode helper(TreeNode root){
if(root==null){
return null;
}
TreeNode left=helper(root.left);//当前点的左子树
TreeNode right=helper(root.right);
//左子树存在
if(left!=null){
left.right=root.right;//左子树最后一右孩子点right指向根节点的右子树
root.right=root.left;//根节点的right指向左子树
root.left=null;//根节点的左子树为空
}
//右子树存在的话返回右子树最后一个点
if(right!=null){
return right;
}
if(left!=null){
return left;
}
return root;
}
}