二叉树展开为链表
如果root节点的左子树不空,将左子树的右链插入到root的右子树位置。如果左子树为空,则将遍历root的右节点。
/**
* 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 {
TreeNode pre = null;
public void flatten(TreeNode root) {
while (root != null) {
TreeNode p = root.left;
if (p != null) {
while (p.right != null) p = p.right;
p.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
}