题目描述
方法思路
Approach1:
class Solution{
//Runtime: 6 ms, faster than 99.92%
//Memory Usage: 39.2 MB, less than 5.09%
private TreeNode next = null;
public void flatten(TreeNode root) {
if (root == null) return;
flatten(root.right);
flatten(root.left);
root.right = next;
root.left = null;
next = root;
}
}
Approach2:
class Solution{
//it is DFS so u need a stack.
//Dont forget to set the left child to null, or u'll get TLE. (tricky!)
//Runtime: 7 ms, faster than 75.79%
//Memory Usage: 38.2 MB, less than 11.03%
public void flatten(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stk = new Stack<TreeNode>();
stk.push(root);
while (!stk.isEmpty()){
TreeNode curr = stk.pop();
if (curr.right!=null)
stk.push(curr.right);
if (curr.left!=null)
stk.push(curr.left);
if (!stk.isEmpty())
curr.right = stk.peek();//查看此堆栈顶部的对象,而不从堆栈中删除它。
curr.left = null; // dont forget this!!
}
}
}
Approach3:
class Solution{
//Runtime: 6 ms, faster than 99.92%
//Memory Usage: 38.1 MB, less than 15.45%
//This solution is based on recursion. We simply flatten left and right subtree and paste each sublist to the right child of the root. (don't forget to set left child to null)
public void flatten(TreeNode root) {
if (root == null) return;
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
flatten(left);
flatten(right);
root.right = left;
TreeNode cur = root;
while (cur.right != null) cur = cur.right;
cur.right = right;
}
}