版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/89646962
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
题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
题目分析:flatten左子树,接到右边,不断递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) {
return;
}
while (root != null) {
TreeNode lTree = root.left;
TreeNode rTree = root.right;
flatten(lTree);
// link flattened left node to root's right
root.right = lTree;
root.left = null;
// go to the previous right node
while (root.right != null) {
root = root.right;
}
root.right = rTree;
root = root.right;
}
}
}