知识点

解题思路

定义全局的curr树,深度优先遍历root,每次将curr的左子树设为空,右子树为root的值,如果root的左右子树不为空,又将root的左右子树进行方法递归设置curr的右子树。最后返回指向curr根节点的ans。

Java题解

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return TreeNode类
     */
     TreeNode ans;
     TreeNode curr;
    public TreeNode flattenTree (TreeNode root) {
        // write code here
        if(root == null) return null;
        ans = new TreeNode(0);
        curr = ans;
        fun(root);
        return ans.right;
    }

    public void fun(TreeNode root){
        curr.left = null;
        curr.right = new TreeNode(root.val);
        curr = curr.right;
        if(root.left != null){
            fun(root.left);
        }
        if(root.right != null){
            fun(root.right);
        }
    }
}