原题链接114. Flatten Binary Tree to Linked List
【思路】
基本思路就是将右子树挂在左子树最右边,并用左子树替换右子树。将root左子树置空,root指向右子树根节点。如此循环,直到root为空:
public void flatten(TreeNode root) {
while (root != null) {
if (root.left != null) {
TreeNode temp = root.left;
while (temp.right != null)
temp = temp.right;
temp.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
225 / 225 test cases passed. Runtime: 1 ms Your runtime beats 34.42% of javasubmissions.
递归解法其实是一种中序遍历,将每个节点的左子树右边,右子树挂在左子树的最右边:
public void flatten(TreeNode root) {
flattenSubTree(root);
}
public TreeNode flattenSubTree(TreeNode root) {
if (root == null || root.left == null && root.right == null) return root;
TreeNode leftSub = root.left;
TreeNode rightSub = root.right;
root.left = null;
if (leftSub != null) {
root.right = leftSub;
TreeNode temp = flattenSubTree(leftSub);
temp.left = null;
if (rightSub != null) temp.right = rightSub;
else return temp;
}
return flattenSubTree(rightSub);
}
225 / 225
test cases passed. Runtime: 1 ms Your runtime beats 34.42% of javasubmissions.
欢迎优化!
本文深入探讨了如何通过迭代和递归方式将二叉树结构扁平化为链表,重点阐述了核心算法实现及性能优化。包括详细步骤、代码实现、测试案例和运行效率分析。
1913

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



