iT邦幫忙

第 11 屆 iThome 鐵人賽

0
自我挑戰組

刷題記錄與人生分享系列 第 31

DAY31 Flatten Binary Tree to Linked List

  • 分享至 

  • xImage
  •  

題目:

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
!https://ithelp.ithome.com.tw/upload/images/20191002/2011972429x5xcSKI7.png

解題思路:

我個人認為非遞迴比遞迴解法還更好理解,先把左節點移置右節點後把根節點往右節點移動,以此循環值到條件不符合為止。
https://ithelp.ithome.com.tw/upload/images/20191002/20119724kqdBS0RZfA.png
圖片來源: https://www.cnblogs.com/grandyang/p/4293853.html

C版本:

void flatten(struct TreeNode* root) {
    while(root != NULL) {  
            if(root->left != NULL) {  
                struct TreeNode* ptr = root->left;  
                while(ptr->right != NULL) 
                    ptr = ptr->right;  
                ptr->right = root->right;  
                root->right = root->left;  
                root->left = NULL;  
            }  
            root = root->right;  
        }  
}

Javascript版本:

while(root != null) {  
   if(root.left != null) {  
      var ptr = root.left
      while(ptr.right != null) 
        ptr = ptr.right;  
        ptr.right = root.right;  
        root.right = root.left;  
        root.left = null;  
      }  
      root = root.right;  
}

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

Sometimes the right path is not the easiest one.
有時對的那條路,往往是最難走的


上一篇
DAY30 Find Minimum in Rotated Sorted Array II
下一篇
DAY32 南部求職分享 Part1
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言