LeetCode | Flatten Binary Tree to Linked List

来源:互联网 发布:基于tensorflow的应用 编辑:程序博客网 时间:2024/06/17 09:06

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.

思路:先做一次先序遍历,把结点存储在一个向量中,最后把向量中的每个元素p(i)作为它上个元素p(i-1)的右结点,且p(i-1)的左结点为空。除了最后那个元素,其左右结点都为空。


/** * 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){path(root);int i;TreeNode* t = root;root->left = NULL;for(i=1; i<v.size(); ++i){t->right = v[i];t = t->right;t->left = NULL;}t->right = NULL;}    }void path(TreeNode *root)//递归,先序遍历{if(root){v.push_back(root);if(root->left)path(root->left);if(root->right)path(root->right);}}private:vector<TreeNode*> v;//存储先序遍历的结果};


0 0
原创粉丝点击