LeetCode 114. Flatten Binary Tree to Linked List 二叉树展开为链表(Java)
程序员文章站
2022-03-07 23:40:08
...
题目:
Given a binary tree, flatten it to a linked list in-place.
解答:
本题主要是怎样在原地 将二叉树转换为链表
我采用的思路如下:
- 判断 root.left 是否为空,若不为空,则找到 temp 节点为左子树的最右节点
- 将 root 的右子树连接到左子树的最右节点 temp
- 将左子树连接为 root 的右子树,并将 root 左子树置空
- 循环直至新的左子树为空
class Solution {
public void flatten(TreeNode root) {
while(root != null) {
if(root.left == null) {
root = root.right;
} else {
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;
}
}
}
} n
推荐阅读
-
LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)
-
Leetcode刷题java之114. 二叉树展开为链表
-
114. Flatten Binary Tree to Linked List(二叉树展开为链表)
-
【leetcode】114. 二叉树展开为链表(Flatten Binary Tree to Linked List)(DFS)
-
LeetCode: 114. Flatten Binary Tree to Linked List
-
LeetCode 114. Flatten Binary Tree to Linked List 二叉树展开为链表(Java)
-
leetcode题解(四十三):114. Flatten Binary Tree to Linked List
-
LeetCode·114. Flatten Binary Tree to Linked List
-
Leetcode 114. Flatten Binary Tree to Linked List