题目描述

方法思路
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;
}
}

本文详细解析了二叉树扁平化的三种高效算法:递归法、迭代法(使用栈)及Morris遍历。通过具体代码实现,展示了如何将二叉树转换为链表,同时保持节点的相对顺序,且不使用额外的数据结构。
846

被折叠的 条评论
为什么被折叠?



