leetcode 114. 二叉树展开为链表 java
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
思路:
1.首先,将根节点的右子树,连接到根节点的左子树的最右节点,如下图所示:
2.然后将左子树移动到右边,如下图所示:
3.之后,将根节点的右节点 作为 当前的根节点,循环进行。
/**
* 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)
return;
while(root.right != null || root.left != null){
if(root.left != null){
TreeNode node = root.left;
while(node.right != null){
node = node.right;
}
node.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
}