Flatten Binary Tree to Linked List

来源:互联网 发布:说说大全软件 编辑:程序博客网 时间:2024/06/17 00:26

Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the right pointer in TreeNode as the nextpointer in ListNode.


样例
              1               \     1          2    / \          \   2   5    =>    3  / \   \          \ 3   4   6          4                     \                      5                       \                        6
注意

Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

class Solution {public:    void flatten(TreeNode *root) {        if(root==NULL) return;        if(root->left==NULL&&root->right==NULL) return;        if(root->left) flatten(root->left);        if(root->right) flatten(root->right);        TreeNode* tmp=root->left;        if(tmp==NULL) return;        while(tmp->right){            tmp=tmp->right;        }        tmp->right=root->right;        root->right=root->left;        root->left=NULL;    }};


0 0
原创粉丝点击