二叉樹轉單鏈表

原題

  Given a binary tree, flatten it to a linked list in-place.
  For example,
  Givennode

1
        / \
       2   5
      / \   \
     3   4   6

 

  The flattened tree should look like:算法

1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

 

 

題目大意

  給定一棵二叉樹,將它轉成單鏈表,使用原地算法spa

解題思路

  從根結點(root)找左子樹(l)的最右子結點(x),將root的右子樹(r)接到x的右子樹上(x的右子樹爲空),root的左子樹總體調整爲右子樹,root的左子樹賦空。.net

代碼實現

樹結點類code

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

 

算法實現類get

public class Solution {

    public void flatten(TreeNode root) {
        TreeNode head = new TreeNode(-1);
        head.right = root;
        TreeNode node = head;

        while (node.right != null) {
            node = node.right;
            if (node.left != null) {
                TreeNode end = node.left;
                while (end.right != null) {
                    end = end.right;
                }

                TreeNode tmp = node.right;

                node.right = node.left;
                node.left = null;
                end.right = tmp;
            }
        }

        head.right = null; // 去掉引用方便垃圾回收
    }
}
相關文章
相關標籤/搜索