Tuesday, December 13, 2016

Leetcode/微软 - 114. Flatten Binary Tree to Linked List - dfs

114. Flatten Binary Tree to Linked List(DFS)
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

public class Solution {
    public void flatten(TreeNode root) {
        if(root == null){return;}
        TreeNode leftn = root.left;
        TreeNode rightn = root.right;
        
        flatten(leftn);
        flatten(rightn);
        
        root.left = null;//remove the left node
        root.right = leftn;(ex: 3)
        TreeNode cur = root;(ex: 2)
        while (cur.right != null) cur=cur.right;
        cur.right = rightn;
        (ex:3)      (ex:4)
    }
    
}

No comments:

Post a Comment