LeetCode 897 Increasing Order Search Tree

栏目: 数据库 · 发布时间: 6年前

内容简介:给定一颗二叉搜索树,重新进行排序,使其根节点是最小值,且每个节点都没有左子树,只有一个右子树,最终还要保持该树是一颗二叉搜索树.使用中序遍历即可。

给定一颗二叉搜索树,重新进行排序,使其根节点是最小值,且每个节点都没有左子树,只有一个右子树,最终还要保持该树是一颗二叉搜索树.

例 1:
给予树:

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

输出:

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

解法

使用中序遍历即可。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private TreeNode result = new TreeNode(0);
    private TreeNode dummy = result;

    public TreeNode increasingBST(TreeNode root) {
        if (root == null) {
            return null;
        }
        increasingBST(root.left);
        dummy.right = new TreeNode(root.val);
        dummy = dummy.right;
        increasingBST(root.right);
        return result.right;
    }
}
Runtime: 2 ms, faster than 99.97% of Java online submissions for Increasing Order Search Tree.
Memory Usage: 44.9 MB, less than 59.39% of Java online submissions for Increasing Order Search Tree.

以上所述就是小编给大家介绍的《LeetCode 897 Increasing Order Search Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hibernate

Hibernate

James Elliott / O'Reilly Media, Inc. / 2004-05-10 / USD 24.95

Do you enjoy writing software, except for the database code? Hibernate:A Developer's Notebook is for you. Database experts may enjoy fiddling with SQL, but you don't have to--the rest of the appl......一起来看看 《Hibernate》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

MD5 加密
MD5 加密

MD5 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具