leetcode
leetcode copied to clipboard
欢迎大家给微扰酱找活~
有什么想要更新的题解可以在这里留言哦!
114.二叉树展开为链表,求题解,官方的题解实在没有理解
期望是java解法
比官方题解好懂:
// 递归函数:将二叉树展开为链表
public void flatten(TreeNode root) {
// base case
if (root == null) {
return;
}
// 1.将左右子树展开为链表
flatten(root.left);
flatten(root.right);
// 先记住root的左右链表
TreeNode leftNode = root.left;
TreeNode rightNode = root.right;
// 2.先将left接到root的右边
root.left = null;
root.right = leftNode;
// 3.再将right接到后面
TreeNode cur = root;
while (cur.right != null) {
cur = cur.right;
}
cur.right = rightNode;
}
比官方题解好懂:
// 递归函数:将二叉树展开为链表 public void flatten(TreeNode root) { // base case if (root == null) { return; } // 1.将左右子树展开为链表 flatten(root.left); flatten(root.right); // 先记住root的左右链表 TreeNode leftNode = root.left; TreeNode rightNode = root.right; // 2.先将left接到root的右边 root.left = null; root.right = leftNode; // 3.再将right接到后面 TreeNode cur = root; while (cur.right != null) { cur = cur.right; } cur.right = rightNode; }
好耶 我看看~
蝴蝶忍yyds