题目

image.png

思路

  • 按照先序遍历解决即可

代码

  1. //1.使用栈
  2. public void flatten(TreeNode root) {
  3. if (root == null) return;
  4. Stack<TreeNode> stack = new Stack<>();
  5. stack.push(root);
  6. while (!stack.isEmpty()) {
  7. TreeNode cur = stack.pop();
  8. if (cur.right != null) stack.push(cur.right);
  9. if (cur.left != null) stack.push(cur.left);
  10. cur.right = stack.isEmpty() ? null : stack.peek();
  11. cur.left = null;
  12. }
  13. }
  14. //2.递归
  15. TreeNode prev;
  16. public void flatten(TreeNode root) {
  17. if (root == null) return;
  18. TreeNode right = root.right, left = root.left;
  19. if (prev != null) prev.right = root;
  20. prev = root;
  21. root.left = null;
  22. flatten(left);
  23. flatten(right);
  24. }

二叉树展开为链表