114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List


/**
 * 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;
      Deque<TreeNode> stack = new ArrayDeque<>();
      stack.push(root);
      while(!stack.isEmpty()){
        TreeNode cur = stack.pop();
        if(cur.right != null){
          stack.push(cur.right);
        }
        if(cur.left != null){
          stack.push(cur.left);
        }
        if(!stack.isEmpty()){
          cur.right = stack.peek();
        }
        cur.left = null;
      }
      
    }
}

// change from offer/poll to push/pop made it accepted ?
// Stack uses push/pop/peek

//Queue uses offer/poll/peek



// this is a preorder traversal problem essentially, the little extra thing to do is 
// to connect the cur to the top element in the stack which is waiting to be added to the result list 
// in the basic preorder traversal, in this problem, since its in place, we use cur.right = stack.peek().
// we dont use cur.right = stack.pop(), its because once we pop this elelemt, we need to add its left child and right child if t
// have any . another thing to keep in mind is that cur.left = null , for every cur, to disconnect the previous links 

 

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

posted on 2018-08-09 17:04  猪猪&#128055;  阅读(89)  评论(0)    收藏  举报

导航