标签: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