Clean DFS Solution


  • 0
    N
    public class Solution {
    
    public void flatten(TreeNode root) {
          helper(root);
    }
    
    private TreeNode helper(TreeNode root) {
          if(root==null) {
            return null;
          }
          TreeNode tail = root;
          if(root.left!=null) {
            TreeNode newTail = helper(root.left);
            tail = newTail;
            tail.right = root.right;
            root.right = root.left;
            root.left = null;
          }
          newTail = helper(tail.right);
          tail = newTail!=null? newTail : tail;
          return tail;
       }
    }

Log in to reply
 

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