力扣热门100题之二叉树展开为链表
核心思路3 步超级好记递归展开左子树递归展开右子树拼接把左子树移到右边把原来的右子树接到链表末尾左指针全部设为null完整代码实现/** * 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) { if (root null) return; // 1. 先把左右子树分别展开 flatten(root.left); flatten(root.right); // 2. 把展开后的左子树接到 root 的右边 TreeNode right root.right; // 保存原来的右子树 root.right root.left; root.left null; // 左指针置空 // 3. 找到现在右子树的最后一个节点接上原来的右子树 TreeNode cur root; while (cur.right ! null) { cur cur.right; } cur.right right; } }一句话总结先展开左右 → 左换右 → 末尾接原右 → 左置空