[Leetcode] [tree] [flatten binary tree to linked list]

Source: Internet
Author: User

Link the tree with right in the order of traversal in the forward order.

I thought for a long time, but I didn't have any idea at all. I always thought that the inplace solution was very clever.

Later, I decided to use a variable to record the current access point. It was so witty ~~

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     void flatten(TreeNode *root) {13         now = NULL;14         findRes(root);15     }16 private:17     TreeNode * now;18     void findRes(TreeNode *root) {19         if (root == NULL) {20             return;21         }22         findRes(root->right);23         findRes(root->left);24         root->left = NULL;25         root->right = now;26         now = root;27     }28 };

 

After an AC, I read the question and found that the ideas differ greatly! The version of iteration is clear. Once again, it is also an AC.

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     void flatten(TreeNode *root) {13         if (root == NULL) {14             return;15         }16         stack<TreeNode*> s;17         s.push(root);18         while (!s.empty()) {19             TreeNode * now = s.top();20             s.pop();21             if (now->right != NULL) {22                 s.push(now->right);23             }24             if (now->left != NULL) {25                 s.push(now->left);26             }27             now->left = NULL;28             if (!s.empty()) {29                 now->right = s.top();30             }31         }32     }33 };

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.