leetcode 114: Flatten Binary Tree to Linked List

来源:互联网 发布:电驴下载软件 编辑:程序博客网 时间:2024/04/30 09:24

Use the DFS of course. The idea here is to find the right most node of each subtree (return it) and make the right child be the right child of that right most node. And then move its left child to its right.

/** * 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) {        helper(root);    }    TreeNode* helper(TreeNode* root)    {        if(!root)            return NULL;        if(!root->left&&!root->right)            return root;        TreeNode* p=helper(root->left);//right most node of left subtree        TreeNode* q=helper(root->right);//right most node of right subtree        if(!root->left)            return q;        if(!root->right)        {            root->right=root->left;            root->left=NULL;            return p;        }        p->right=root->right;        root->right=root->left;        root->left=NULL;        return q;    }};


0 0
原创粉丝点击