[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  或者扫描下方二维码关注我
[LeetCode] Flatten Binary Tree to Linked List [39]_第1张图片
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/38322783 )


你可能感兴趣的:(LeetCode,链表,面试,二叉树)