leetcode之Flatten Binary Tree to Linked List

来源:互联网 发布:游戏充值用什么软件 编辑:程序博客网 时间:2024/06/11 05:51

题目:

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.


解答:

在递归的同时对子树进行整理即可


代码如下

/** * 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:    TreeNode* rotate(TreeNode *root)    {        if(root->left == NULL && root->right == NULL)            return root;        TreeNode* l = (root->left == NULL) ? NULL : rotate(root->left);        TreeNode* r = (root->right == NULL) ? NULL : rotate(root->right);        if(l == NULL)            return root;        TreeNode *tmp = root->right;        root->right = l;        while(l->right)            l = l->right;        l->right = tmp;        root->left = NULL;        return root;    }    void flatten(TreeNode* root) {        if(root == NULL)            return;        rotate(root);    }};

0 0
原创粉丝点击