其他分享
首页 > 其他分享> > [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.

Analyse

用二叉树中序遍历的结果生成新的二叉树,中序遍历很容易就写出来了,但生成新的二叉树我卡了好久

问题出在递归和递归函数的传参上

以下面这个二叉树为input

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

第一个要被插入树的节点是1,这个1是在第四层的递归中返回的,将1插入二叉树的头节点后面,再把2查到二叉树头节点后面……

构造树的时候要用到一个头节点,然而每次进入递归时使用的cur是同一个,导致后面的节点将前面的覆盖,我第一次写就出现了所有的左节点都消失了的现象

if (root->left)
{
    InOrder(root->left, cur);
}

我的解决办法是每次都找到树的最右节点再插入

while (cur->right) {cur = cur->right;}

最终代码如下

TreeNode* increasingBST(TreeNode* root) {
    if (root == NULL)
    {
        return root;
    }

    TreeNode* result = new TreeNode(0);
    TreeNode* current = result;
    InOrder(root, current);
    return current->right;
}

void InOrder(TreeNode* root, TreeNode* cur){
    if (root == NULL) return;

    if (root->left)
    {
        InOrder(root->left, cur);
    }

    TreeNode* node = new TreeNode(root->val);

    while (cur->right) {cur = cur->right;}
    cur->right = node;

    if (root->right)
    {
        InOrder(root->right, cur);
    }
}

LeetCode的讨论区还有一种先中序遍历,把结果存到vector里,再通过vector来生成树的做法,这样就简单很多

标签:Search,right,TreeNode,cur,897,Tree,二叉树,null,root
来源: https://www.cnblogs.com/arcsinw/p/10409347.html