1. 程式人生 > >LeetCode:114. Flatten Binary Tree to Linked List(固定二叉樹為連結串列)

LeetCode:114. Flatten Binary Tree to Linked List(固定二叉樹為連結串列)

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

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

方法1:(利用棧的形式)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        if (root == null) return;
        Stack<TreeNode> stk = new Stack<TreeNode>();
        stk.push(root);
        while (!stk.isEmpty()){
            TreeNode curr = stk.pop();
            if (curr.right!=null)  
                 stk.push(curr.right);
            if (curr.left!=null)  
                 stk.push(curr.left);
            if (!stk.isEmpty()) 
                 curr.right = stk.peek();
            // 它的左子樹要為空
            curr.left = null;  
    }
  }
}

時間複雜度:O(n)

空間複雜度:O(1)


方法2:遞迴形式

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        falttenForList(root, null);
    }
    private TreeNode falttenForList(TreeNode root, TreeNode cur) {
        if (root == null)
            return cur;
        cur = falttenForList(root.right, cur);
        cur = falttenForList(root.left, cur);
        root.left = null;
        root.right = cur;
        return root;
        
    }
}

時間複雜度:O(n)

空間複雜度:O(n)


原始碼github地址:https://github.com/zhangyu345293721/leetcode