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  
 

Constraints:

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.

这题很简单,有序,则直接中序遍历,在遍历的时候遇到访问节点值的时候,直接插入结果树的右节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* increasingBST(TreeNode* root) {
        TreeNode *res_root = nullptr;
        TreeNode *parent = nullptr;
        dfs(root, res_root, parent);
        return res_root;
    }

    void dfs(TreeNode *node, TreeNode *&root, TreeNode *&parent) {
        if (nullptr != node->left) {
            dfs(node->left, root, parent);
        }
        if (nullptr == parent) {
            parent = new TreeNode(node->val);
            root = parent;
        } else {
            parent->right = new TreeNode(node->val);
            parent = parent->right;
        }
        if (nullptr != node->right) {
            dfs(node->right, root, parent);
        }
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day