Flatten Binary Tree to Linked List 将二叉树转为链表

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
 
     
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
//前序遍历
    void flatten(TreeNode *root) {
        solve(root);
    }
    
    TreeNode *solve(TreeNode* root)
    {
        if(root==NULL||(root->left==NULL&&root->right==NULL))
            return root;
        TreeNode* left=root->left;
        TreeNode* right=root->right;
        root->left=NULL;
        if(left!=NULL)
        {
            root->right=left;
            root=solve(left);
        }
        if(right!=NULL)
        {
            root->right=right;
            root=solve(right);
        }
        return root;
    }
};

你可能感兴趣的:(LeetCode,OJ,ACM,精选)