【Leetcode】Flatten Binary Tree to Linked List

来源:互联网 发布:索尼授权网络经销商 编辑:程序博客网 时间:2024/06/05 18:01
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)     {if (!root) return;TreeNode *start=NULL,*end=NULL;flat(root,start,end);    }void flat(TreeNode *root, TreeNode *&front, TreeNode *&tail){if (!root->left && !root->right){front = tail = root;return;}TreeNode *start = NULL,*end = NULL,*start0 = NULL,*end0 = NULL;if(root->left)flat(root->left, start, end);if(root->right)flat(root->right, start0, end0);if (!start)start = start0;elseend->right = start0;root->left = NULL;root->right = start;front = root;if (start0)tail = end0;elsetail = end;}};


 

原创粉丝点击