您的位置:首页 > 其它

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

2015-04-28 11:23 447 查看


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

[code]
/**
 * 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;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐