0114. Flatten Binary Tree to Linked List (M)
Posted 墨云黑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了0114. Flatten Binary Tree to Linked List (M)相关的知识,希望对你有一定的参考价值。
Flatten Binary Tree to Linked List (M)
题目
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \\
2 5
/ \\ \\
3 4 6
The flattened tree should look like:
1
\\
2
\\
3
\\
4
\\
5
\\
6
题意
将一个二叉树的结构变为只有右子树的一直链,且顺序为原二叉树的前序遍历。
思路
方法有点像 Morris Traversal:如果当前结点root存在左子树,则将该结点的右子树接在其左子树最右结点的右边,再将root的左子树变为右子树,令 root = root.right 重复上述操作。
代码实现
Java
class Solution {
public void flatten(TreeNode root) {
while (root != null) {
if (root.left != null) {
TreeNode x = root.left;
while (x.right != null) {
x = x.right;
}
x.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
}
javascript
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var flatten = function (root) {
while (root) {
if (root.left) {
let tmp = root.left
while (tmp.right) tmp = tmp.right
tmp.right = root.right
root.right = root.left
root.left = null
}
root = root.right
}
}
以上是关于0114. Flatten Binary Tree to Linked List (M)的主要内容,如果未能解决你的问题,请参考以下文章
114. Flatten Binary Tree to Linked List
Flatten Binary Tree to Linked List
Jan 29 - Flatten Binary Tree To Linked List; DFS;
114. Flatten Binary Tree to Linked List