给定一个二叉树,原地将它展开为链表。
代码语言:javascript复制例如,给定二叉树
1
/
2 5
/
3 4 6
将其展开为:
1
2
3
4
5
6
解:
代码语言:javascript复制/**
* 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) {
if (root == null) {
return;
}
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
flatten(left);
flatten(right);
root.right = left;
TreeNode cur = root;
while (cur.right != null) {
cur = cur.right;
}
cur.right = right;
}
}