问题描述
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root) {
def(root);
}
TreeNode def(TreeNode root) {
if(root==null)
return null;
if(root.left==null) {
if(root.right==null)
return root;
else
return def(root.right);
}
if(root.left.left==null&&root.left.right==null) {
if(root.right==null)
{
root.right=root.left;
root.left=null;
return root.right;
}
root.left.right=root.right;
root.right=root.left;
root.left=null;
return def(root.right.right);
}
TreeNode left=def(root.left);
TreeNode right=def(root.right);
left.right=root.right;
root.right=root.left;
root.left=null;
if(right==null)
return left;
return right;
}
}