Flatten Binary Tree to Linked List

来源:互联网 发布:pstn网络 编辑:程序博客网 时间:2024/05/29 03:16

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 {private:    TreeNode *last;//保存上一次访问的叶子节点,也就是list的尾节点public:    void flatten(TreeNode *root) {        last=NULL;        flat(root);    }    void flat(TreeNode *root){        if(!root) return;        if(!root->left&&!root->right){            last=root;            return;        }        if(!root->left){            flat(root->right);            return;        }        if(!root->right){            root->right=root->left;            root->left=NULL;//important            flat(root->right);            return;        }        TreeNode *r = root->right;        root->right=root->left;        root->left=NULL;//important                flat(root->right);        last->left=NULL;        last->right=r;//连接起来        flat(r);    }    };










0 0