原文链接 [链接] Description: Given a 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 lef ..

[每日 LeetCode] 897. Increasing Order Search Tree

原文链接 [每日 LeetCode] 897. Increasing Order Search Tree

Description:

Given a 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:

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

思路:本题要求把二叉树的结点重新排列,使其成为从小到大只有右孩子的二叉树。考虑使用中序遍历的迭代方法,对每个结点入栈,出栈时先访问左结点,然后中结点,最后把右指针和下一个入栈的结点链接起来。


C++ 代码

/**
 * 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* increasingBST(TreeNode* root) {
        TreeNode *head = new TreeNode(0), *pre = head;
        stack<TreeNode*> stc;
        while (root || !stc.empty()) {
            while (root) {
                stc.push(root);
                root = root -> left;
            }
            root = stc.top();
            stc.pop();
            pre -> right = root;
            pre = pre -> right;
            root -> left = NULL;
            root = root -> right;
        }
        return head -> right;
    }
};

运行时间:40ms

运行内存:16.9M

  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    154 引用 • 36 回帖 • 1 关注
  • Tree
    33 引用 • 5 回帖
  • Easy
    101 引用 • 10 回帖
回帖   
请输入回帖内容...