JAVA 1ms Solution


  • 0
    Y
    /**
     * Definition for a binary tree node.
     * 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;
            flat(root);
        }
        
        public TreeNode flat(TreeNode node){
            if(node.left == null && node.right == null)
                return node;
            TreeNode tmp = new TreeNode(0);
            TreeNode right = node.right;
            if(node.left != null){
                tmp = flat(node.left);
                tmp.right = node.right;
                node.right = node.left;
                node.left = null;
                
            }
            if(right != null){
                tmp = flat(right);
            }
            return tmp;
        }
    }

Log in to reply
 

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