114. Flatten Binary Tree to Linked List

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
        }
        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的主要内容,如果未能解决你的问题,请参考以下文章