题目
官方题解好有意思
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root) {
while(root != null){
//找左子树的最右节点
//如果不存在左子树
if(root.left == null){
root = root.right;
}else{
//找到左子树的最右节点
TreeNode pre = root.left;
while(pre.right != null){
pre = pre.right;
}
//该节点的右节点接右子树
pre.right = root.right;
// 根节点的右子树更新为左子树
root.right = root.left;
// 根节点的左子树记得置空!!!
root.left = null;
//根节点指向下一个节点
root = root.right;
}
}
}
}
结果