[LeetCode] Flatten Binary Tree to Linked List [39]

題目

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.

Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

原題鏈接(點我)


解題思路

本題的意思是將二叉樹按照先序遍歷的方式,串成一個鏈表。

代碼實現

void flatten( TreeNode *root){
     if (root == NULL) return;
     flatten(root->left);
     flatten(root->right);
     if (root->left == NULL) return ;
     TreeNode *pre = root->left;
     wihle (pre->right != NULL) 
          pre = pre->right;
     pre->right = root->right;
     root->right = root->left;
     root->left = NULL;
}
如果你覺得本篇對你有收穫,請幫頂。
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.
你可以搜索公衆號:swalge 或者掃描下方二維碼關注我

(轉載文章請註明出處: http://blog.csdn.net/swagle/article/details/38322783 )


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章