找前驱结点,o(n) o(1)
// 左节点为空,不需要进行其他操作
// 左节点不为空,左子树的最后一个结点被访问之后,右结点便被访问
// 该结点的左子树中最后一个被访问的便是左子树中最右边的结点
// 具体做法:找到左子树的最右结点,将当前结点赋给了这个点,同时左子树的左结点要为空
// 然后当前结点的左结点赋给了其右结点
class Solution {
public void flatten(TreeNode root) {
dfs(root);
}
public TreeNode dfs(TreeNode root){
if(root == null) return null;
TreeNode left = dfs(root.left);
TreeNode right = dfs(root.right);
if(left != null){
left.right = root.right;
left.left = null;
root.right = root.left;
}
root.left = null;
if(right != null) return right;
else if(left != null) return left;
return root;
}
}