二叉树展开为链表
思路
1、分别将root的左右子树拉平。
2、左子树作为新的右子树,旧的右子树连接到新右子树的末尾。
代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
// 将一棵树展开成单链表,并返回根节点。
var flatten = function(root) {
if(root==null) return null;
let left = flatten(root.left);
let right = flatten(root.right);
root.left = null;
root.right = left;
// 找到左子树的末尾
let p = root;
while(p.right!=null){
p = p.right;
}
p.right = right;
return root;
};