1. 程式人生 > >897. Increasing Order Search Tree(Tree)

897. Increasing Order Search Tree(Tree)

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

題目:將原二叉搜尋樹進行調整,使得每個節點只有右子節點。

例如:

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  

思路:
儲存一個全域性newroot指標,採用中序遍歷的方法,
每次遍歷時: newroot->right = root; root->left = NULL;newroot = root; (root為當前節點)

程式碼:

class Solution {
public:
    
    void In_Order(TreeNode *root){
             if(!root) return;
        
             In_Order(root->left);
             
             if(!newroot) {//找到第一個節點
                newroot = ret = root;  
             }
        
             else {  //後續節點調整
                 newroot->right = root;
                 root->left = NULL;
                 newroot = root;
             }
        
             In_Order(root->right);
        
    }
    
    TreeNode* increasingBST(TreeNode* root) {
              ret = newroot = NULL;
              In_Order(root);
        
              return ret;
    }
    
private:
    TreeNode *newroot;
    TreeNode *ret;
};