这个算法写的太烂,大家直接看新博文,地址:
[leetcode]Flatten Binary Tree to Linked List
Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
状态不好就要看书,不要敲代码。囧
这道题目要求将一个二叉排序树转换成一个list,但是要就地取材in-place,不能有额外空间。典型的,是将左子树插到根节点的右子树上,然后再将右子树插到队尾,典型的前序遍历。
TreeNode tail;//记录队尾节点 public void flattern(TreeNode root){ tail = root; doFlate(root); } private void doFlate(TreeNode root){ if(root == null || (root.left == null && root.right == null)){ return; } TreeNode left = root.left; TreeNode right = null ; tail = root; if(root.right != null){ right = root.right; } if(left != null){ root.right = left; root.left = null; tail = left; } doFlate(left);//处理左子树 if(right != null){//将右子树插到队尾 tail.right = right; tail = right; } doFlate(right);//再处理右子树 }
相关推荐
java java_leetcode-114-flatten-binary-tree-to-linked-list
python python_leetcode题解之114_Flatten_Binary_Tree_to_Linked_List
javascript js_leetcode题解之114-flatten-binary-tree-to-linked-list.js
leetcode做过的LeetCode的题目记录一下。对一些比较经典的题型进行分类总结。数据结构 数组 字符串 队列 链表 双指针 栈 堆 树 二叉搜索树 字典树 线段树 并查集 哈希表 图基础... Flatten Binary Tree to Linked List
leetcode 答案leetcode 的工具 这个项目提供了一些工具来更容易地测试 leetcode 答案。 树:切片 <-> TreeNode 此工具有助于将切片转换为 TreeNode,反之亦然。 Slice2TreeNode: []interface{} -> *model....
- **Flatten Binary Tree to Linked List**:将二叉树展平为单链表。 - **Validate Binary Search Tree**:验证一个二叉树是否为二叉搜索树。 - **Recover Binary Search Tree**:恢复二叉搜索树中的两个错误节点...
* [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue](https://github.com/kamyu104/LeetCode#queue) * [Heap]...
5. **Flatten Binary Tree to Linked List** (二叉树展开为链表): 这是一个关于树的层次遍历的问题,可以使用广度优先搜索(BFS)策略,利用队列(如Java的`Queue`接口)来实现。 6. **Merge Sorted Array** (合并...
flatten_binary_tree_to_linked_list Java 中等的 100.00% 100.00% binary_tree_pruning Java 中等的 100.00% 100.00% insert_into_a_binary_search_tree Java 中等的 100.00% 100.00% maximum_level_sum_of_a_...
**三、Flatten Binary Tree to Linked List** LeetCode的第114题,要求将二叉树扁平化为单链表,这个问题可以通过分治策略解决。基本步骤如下: 1. **从最简单的case开始**:对于只有一个元素的树,直接返回,即空...