DFS with easy understanding


  • 0
    Y
    public class Solution {
        public void flatten(TreeNode root) {
            if (root == null) {
                return;
            }
            TreeNode left = root.left;
            TreeNode right = root.right;
            root.left = null;
            
            // appear with the /**/ below at the same time
            //root.right = null
            
            flatten(left);
            flatten(right);
            if (left != null) {
                root.right = left;
                while (left.right != null) {
                    left = left.right;
                }
                left.right = right;
            }
            // appear with the // above at the same time
            /*
            else {
                root.right = null
            }
            */
        }
    }
    '''

Log in to reply
 

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