码迷,mamicode.com
首页 > 其他好文 > 详细

114. Flatten Binary Tree to Linked List

时间:2018-08-09 18:31:55      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:ble   val   ext   ==   queue   code   ever   public   not   

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;
        }
        Stack<TreeNode> stack = new Stack<>();
        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()){ // check this , for the last node, stack.peek() is gonna be null exception, for the last element , its right and left both are null in the tree, so cur.right == null without doing anything
                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 

// cur.left = null
  

 

114. Flatten Binary Tree to Linked List

标签:ble   val   ext   ==   queue   code   ever   public   not   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450621.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!