Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
思路:可以采用前序遍历,然后进行赋值。这里使用递归法解题。root的左子树=null,右子树=左子树的递归+右子树的递归。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
treetolist(root);
}
private TreeNode treetolist(TreeNode root){
if(root==null) return null;
TreeNode right=treetolist(root.right);
root.right=treetolist(root.left);
root.left=null;
TreeNode temp=root;
while(temp.right!=null){
temp=temp.right;
}
temp.right=right;
return root;
}
}