Title:

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 a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* tail;
    Solution(){
        tail = NULL;
    }
    void flatten(TreeNode* root) {
        maker(root);
    }
    void maker(TreeNode* p){
        if (!p)
            return ;
        TreeNode* left = p->left;
        TreeNode* right = p->right;
        if (tail){
            tail->right = p;
            tail->left = NULL;
        }
        tail = p;
        maker(left);
        maker(right);
    }
};

 


非递归的更简洁。使用栈,让右节点先进去。这样栈顶就是左节点,所以在两个子节点进栈之后,让当前root节点的右节点指向栈顶
/**
 * 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) {
        if (root == nullptr) 
            return;
        stack<TreeNode*> s;
        s.push(root);
        while (!s.empty()) {
            auto p = s.top();
            s.pop();
            if (p->right)
                s.push(p->right);
            if (p->left)
                s.push(p->left);
            p->left = nullptr;
            if (!s.empty())
                p->right = s.top();
        }
    }
};

 

相关文章:

  • 2021-05-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-09
  • 2021-07-14
  • 2022-01-06
  • 2021-06-18
  • 2021-12-17
  • 2021-11-04
相关资源
相似解决方案