114. Flatten Binary Tree to Linked List(unsolved)

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

解答:这道题其实思路比较简单,但是可能编程上要考虑很多意外情况。
简单来说,就是把左子节点中最靠右的叶子节点指向右子节点,然后把整个左子节点挪到右边。然后root往右子节点走一步。如此递归下去。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void change(TreeNode* root)
    {
        while(root)
        {
           if(root->left&&root->right)  
           {
               TreeNode* t=root->left;
               while(t->right!=NULL)
               {
                   t=t->right;
               }
               t->right=root->right;

           }
           if(root->left)
               root->right=root->left;
           root->left=NULL;
           root=root->right;
        }
    }
    void flatten(TreeNode* root) {
           change(root);
    }

};

你可能感兴趣的:(leetcode算法心得)