题目要求
给你二叉树的根结点 root ,请你将它展开为一个单链表:
- 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
- 展开后的单链表应该与二叉树 先序遍历 顺序相同。
思路:
- 将root的左右子树均拉平
- 将root的左右子树均使用临时变量保存。
TreeNode left = root.left;
TreeNode right = root.right;
- 将root的左子树挂在root的右指针下,同时将root的左指针置空
root.left = null;
root.right = left;
- 遍历当前root的右子树,找到右子树的最后一个节点,做后将先前保存的右子树挂在当前右子树的最后一个节点下。
// 注意再此处不可以写成TreeNode curRight = root.right; 因为原先root可能没有左子树,若该假设成立,则root.right 将为 null;
TreeNode curRight = root;
while(curRight.right != null) {
curRight - curRight.right;
}
curRight.right = right;
- 由下到上周而复始
code
/**
* 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) {
process(root);
}
private void process(TreeNode root) {
if (root == null) {
return;
}
process(root.left);
process(root.right);
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
root.right = left;
TreeNode curRight = root;
while (curRight.right != null) {
curRight = curRight.right;
}
curRight.right = right;
}
}
注意:磁体也可以使用从上到下(使用先序遍历框架)