[LeetCode]Flatten Binary Tree to Linked List

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

click to show hints.

Subscribe to see which companies asked this question

題解:


code:

public class Solution {
    public void flatten(TreeNode root) {
        
        if( root != null)
        {
           flatten(root.right);
           if(root.left != null)
           {
               flatten(root.left);
               TreeNode node = root.left;
               while(node.right != null)
               {
                   node = node.right;
               }
               node.right = root.right;
               root.right = root.left;
               root.left = null;
           }
        }
    }
}
發佈了298 篇原創文章 · 獲贊 9 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章