[leetcode] 114. Flatten Binary Tree to Linked List 解题报告

来源:互联网 发布:苹果笔记本开淘宝店 编辑:程序博客网 时间:2024/06/05 20:56

题目链接:https://leetcode.com/problems/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

思路:思路比较简单,就是递归的将root的左子树接到右子树的位置,然后将右子树接到左子树后面。要注意的是左子树移到右子树之后要将左子树位置都置为NULL。

代码如下:

/** * 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 flatten(TreeNode* root) {        if(!root) return;        flatten(root->left);        flatten(root->right);        auto val = root->right;        root->right = root->left;        root->left = NULL;        while(root->right) root = root->right;        root->right = val;    } };



0 0
原创粉丝点击