leetcode114 二叉树展开为链表
题目详情
题目解析(递归)
- 将左子树转化为链表,并插入到右子树的位置
- 将原来的右子树转化为链表,并插入到新插入的右子树后面
- 将左子树置为null
1
/ \
2 5
/ \ \
3 4 6
//将 1 的左子树插入到右子树的地方
1
\
2 5
/ \ \
3 4 6
//将原来的右子树接到左子树的最右边节点
1
\
2
/ \
3 4
\
5
\
6
//将 2 的左子树插入到右子树的地方
1
\
2
\
3 4
\
5
\
6
//将原来的右子树接到左子树的最右边节点
1
\
2
\
3
\
4
\
5
\
6
......
Java代码实现
public class Solution {
public TreeNode flatten(TreeNode root){
if(root == null)
return root;
if(root.left == null && root.right == null)
return root;
if(root.left == null){
root.right = flatten(root.right);
return root;
}
if(root.right == null){
root.right = flatten(root.left);
root.left = null;
return root;
}
TreeNode left = flatten(root.left);
TreeNode leftR = left;
while(leftR.right != null)
leftR = leftR.right;
leftR.right = flatten(root.right);
root.right = left;
root.left = null;
return root;
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int val){
this.val = val;
}
}
}
非递归方法
public class Solution2 {
public TreeNode flatten(TreeNode root){
if(root == null)
return root;
TreeNode resroot = root;
while(root != null){
if(root.left == null){
root = root.right;
}else{
TreeNode pre = root.left;
while(pre.right != null){
pre = pre.right;
}
pre.right = root.right;
root.right = root.left;
root.left = null;
root = root.right;
}
}
return resroot;
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int val){
this.val = val;
}
}
}