See the problem! LeetCode_114_Flatten_Binary_Tree
What’s more, keep in mind the requirement that flatten it to a linked list in place
See the answer code.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
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;
}
}
}
More important, don’t forget cur.left = null
,or you’ll get TLE
Reference:cbmbbz