I don't know why I code is worng, anyone can help me?


  • 0
    F
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
    
        
        public void flatten(TreeNode root) {
            if(root == null)
            return;
            
            TreeNode newTree = new TreeNode(root.val);
            
            dTraverse(newTree,root);
            root = newTree;
            
        }
        
        public void dTraverse(TreeNode mtree, TreeNode root){
            if(root ==null)
            return;
             if(root.left  != null){
                TreeNode left = new TreeNode(root.left.val);
                mtree.right = left;
            }
            dTraverse(mtree.right,root.left);
          
           
            if(root.right !=null){
                TreeNode right = new TreeNode(root.right.val);
                mtree.right = right;
            }
             dTraverse(mtree.right,root.right);
        }
    }

  • 0
    H

    When the recursive function returns, it will get the local mtree, which is not the newest mtree.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.