114. Flatten Binary Tree to Linked List

问题:

拉平二叉树 -> 只有right分支的链表。

For example, given the following tree:
    1
   / \
  2   5
 / \   \
3   4   6
The flattened tree should look like:
1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

  

解法:Binary Tree(二叉树)

递归做法:

  • base:root==null,直接返回
  • 对每个节点node:
    • 递归拉平node->left,node->right
    • 对已经拉平的两棵子树:rightleft
      • node->right指向原来的left,node->left=null
      • node->right的最后一个right节点->right指向原来的right

代码参考:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     //right = node.right; left = node.left;
15     //1.node.right = left
16     //2.node.right.last.right = right
17     void flatten(TreeNode* root) {
18         if(!root) return;
19         
20         flatten(root->left);
21         flatten(root->right);
22         
23         TreeNode* left = root->left;
24         TreeNode* right = root->right;
25         
26         //1.node.right = left
27         root->left = nullptr;
28         root->right = left;
29         //2.node.right.last.right = right
30         TreeNode* p = root;
31         while(p->right) {
32             p = p->right;
33         }
34         p->right = right;
35     }
36 };

 

posted @ 2020-09-22 11:26  habibah_chang  阅读(125)  评论(0编辑  收藏  举报