问题原文https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/description/
方法:递归
public void flatten(TreeNode root) {
if(root == null) return;
TreeNode left = root.left;
TreeNode right =root.right;
flatten(left);
flatten(right);
root.left = null;
if(left == null && right == null) return;
if(left == null) {
root.right = right;
return;
}
if(right == null) {
root.right = left;
return;
}
TreeNode current = left;
while(current.right!=null) {
current = current.right;
}
current.right = right;
root.right = left;
}
本文介绍了一种将二叉树通过递归方式展平为链表的方法。该方法首先递归展平左右子树,然后重新连接节点,最终使每个节点的左子节点为空,右子节点指向原二叉树中的下一个节点。
825

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



