***(leetcode) (tree) Flatten Binary Tree to Linked List

来源:互联网 发布:上海软件市场 编辑:程序博客网 时间:2024/04/30 10:57

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.

思路:递归,将左右子树 flatten后,调节位置即可,但是不要忘了left要置为NULL!!!!

/** * 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==NULL)            return;        TreeNode *tmp=NULL;        if(root->left!=NULL){            flatten(root->left);            tmp = root->left;            while(tmp!=NULL&&tmp->right!=NULL)                tmp=tmp->right;        }            if(root->right!=NULL)            flatten(root->right);        if(tmp!=NULL){            tmp->right=root->right;            root->right = root->left;            root->left=NULL; // left要置为空,这个地方没注意,一直runTime error OJ的出错的测试例子这部分还不会影响,艹        }    }};

非递归的方法: 类似于调整最小堆,从上往下依次调整
class Solution {public:    void flatten(TreeNode *root) {        if(root==NULL)            return;       while(root!=NULL){           if(root->left!=NULL){                TreeNode *pre = root->left;                while(pre->right!=NULL)                     pre=pre->right;                pre->right=root->right;                root->right=root->left;                root->left=NULL;           }           root = root->right;       }    }};


0 0
原创粉丝点击