897. Increasing Order Search Tree*

897. Increasing Order Search Tree*

https://leetcode.com/problems/increasing-order-search-tree/

题目描述

Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

Example 1:

Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]

       5
      / \
    3    6
   / \    \
  2   4    8
 /        / \ 
1        7   9

Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

 1
  \
   2
    \
     3
      \
       4
        \
         5
          \
           6
            \
             7
              \
               8
                \
                 9  

Note:

  • The number of nodes in the given tree will be between 1 and 100.
  • Each node will have a unique integer value from 0 to 1000.

C++ 实现 1

中序遍历. 但需要注意的是, 当对 root 节点的左子树做了变换之后, 得到一串链表, 要用链表的最后一个节点来连接当前节点, 为了达到这个目的, 需要引入一个额外的节点 prev, 用来记录当前节点的前驱. 因此在 inorder 函数中, 核心的步骤:

prev->right = root;  // 前一个节点连接当前的节点
prev = root;  // 更新 prev = root, 即当前节点在下一次递归时是下一个新 root 的前驱
prev->left = nullptr;  // 另外不要忘了将当前节点的 left 指针置为空

完整代码如下, 引入 dummy 这个虚拟节点, 有很大的好处. 以后处理链表问题经常会看到我用类似的方法:

/**
 * 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 {
private:
    TreeNode *prev;
    void inorder(TreeNode *root) {
        if (!root) return;
        inorder(root->left);
        prev->right = root;
        prev = root;
        prev->left = nullptr;
        inorder(root->right);
    }
public:
    TreeNode* increasingBST(TreeNode* root) {
        TreeNode *dummy = new TreeNode(0);
        prev = dummy;
        inorder(root);
        return dummy->right;
    }
};
发布了327 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104464899