原题地址:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
题目描述:
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
将其展开为:
解题方案:
和Morris有点像,不过是把root的左子树放到右边,再将原来的右子树接到原左子树的最右结点上。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
while(root != null)
{
if(root.left != null)
{
TreeNode tmp = root.right;
root.right = root.left;
root.left = null;
TreeNode t = root.right;
while(t.right != null)
{
t = t.right;
}
t.right = tmp;
}
root = root.right;
}
}
}