LeetCode-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:

  • 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.

题意:将一颗二叉搜索树转化为一颗每个节点仅有右节点,没有左节点的二叉树,并且节点是有序的;

解法:二叉搜索树是满足根节点的值大于左节点而小于右节点,因此,对二叉搜索树进行中序遍历得到的序列就是用于构造新二叉树的序列;

Java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //保存中序遍历的节点值
    private List<Integer> nodes = new ArrayList<>();
    
    public TreeNode increasingBST(TreeNode root) {
        if (root == null) return null;
        getNodes(root);
        TreeNode tree = new TreeNode(nodes.get(0));
        TreeNode treeNext = tree;
        for (int i = 1; i < nodes.size(); i++) {
            TreeNode temp = new TreeNode(nodes.get(i));
            treeNext.right = temp;
            treeNext = temp;
        }
        return tree;
    }
    
    //得到二叉搜索树的中序遍历节点值
    private void getNodes(TreeNode root) {
        if (root.left == null && root.right == null) {
            nodes.add(root.val);
            return;
        }
        if (root.left != null) getNodes(root.left);
        nodes.add(root.val);
        if (root.right != null) getNodes(root.right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值