LeetCode : 114. Flatten Binary Tree to Linked List 将二叉树转成链表

Love The Way You Lie 2021-06-24 16:11 383阅读 0赞

试题
Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

  1. 1
  2. / \
  3. 2 5
  4. / \ \
  5. 3 4 6

The flattened tree should look like:

  1. 1
  2. \
  3. 2
  4. \
  5. 3
  6. \
  7. 4
  8. \
  9. 5
  10. \
  11. 6

代码
先序遍历是将前一个节点地址记录下来。不过这里边有个注意点就是:你在处理当前节点时会导致上一个节点的left和next值发生变化,需要用tmp变量存一下。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. TreeNode pre = new TreeNode(0);
  12. TreeNode head = pre;
  13. public void flatten(TreeNode root) {
  14. if(root==null) return;
  15. preOrder(root);
  16. root = head.right;
  17. }
  18. public void preOrder(TreeNode root){
  19. if(root==null) return;
  20. TreeNode tmpRight = root.right;
  21. TreeNode tmpLeft = root.left;
  22. pre.left = null;
  23. pre.right = root;
  24. pre = root;
  25. preOrder(tmpLeft);
  26. preOrder(tmpRight);
  27. }
  28. }
  29. private TreeNode prev = null;
  30. public void flatten(TreeNode root) {
  31. if (root == null)
  32. return;
  33. flatten(root.right);
  34. flatten(root.left);
  35. root.right = prev;
  36. root.left = null;
  37. prev = root;
  38. }

发表评论

表情:
评论列表 (有 0 条评论,383人围观)

还没有评论,来说两句吧...

相关阅读