博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - 776. Split BST
阅读量:6568 次
发布时间:2019-06-24

本文共 2173 字,大约阅读时间需要 7 分钟。

Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value.  It's not necessarily the case that the tree contains a node with value V.

Additionally, most of the structure of the original tree should remain.  Formally, for any child C with parent P in the original tree, if they are both in the same subtree after the split, then node C should still have the parent P.

You should output the root TreeNode of both subtrees after splitting, in any order.

Example 1:

Input: root = [4,2,6,1,3,5,7], V = 2Output: [[2,1],[4,3,6,null,null,5,7]]Explanation:Note that root, output[0], and output[1] are TreeNode objects, not arrays.The given tree [4,2,6,1,3,5,7] is represented by the following diagram:          4        /   \      2      6     / \    / \    1   3  5   7while the diagrams for the outputs are:          4        /   \      3      6      and    2            / \           /           5   7         1

Note:

  1. The size of the BST will not exceed 50.
  2. The BST is always valid and each node's value is different.

递归,操作二叉搜索树

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public TreeNode[] splitBST(TreeNode root, int V) {        if (root == null)            return new TreeNode[]{
null, null}; if (root.val == V) { TreeNode right = root.right; root.right = null; return new TreeNode[]{root, right}; } else if (root.val > V) { TreeNode[] nodes = splitBST(root.left, V); TreeNode left = nodes[0]; TreeNode right = nodes[1]; root.left = right; return new TreeNode[]{left,root}; } else { TreeNode[] nodes = splitBST(root.right, V); TreeNode left = nodes[0]; TreeNode right = nodes[1]; root.right=left; return new TreeNode[]{root, right}; } }}

 

转载地址:http://tspjo.baihongyu.com/

你可能感兴趣的文章
WPF TreeView HierarchicalDataTemplate
查看>>
32岁老程序员的现状和尴尬,无奈中透露些许悲凉,有选择却更痛苦
查看>>
WPF MeshGeometry3D
查看>>
puppet cron 模块
查看>>
mysql 协议的ResultsetRow包及解析
查看>>
Ymal格式转Properties格式
查看>>
一个生成全局唯一Sequence ID的高并发工厂类 (Java)
查看>>
调优之系统篇--cpu,内存
查看>>
解决jQuery和其它库的冲突
查看>>
写在除夕夜
查看>>
JAVA中的list去重复
查看>>
JAVA 代码里中文乱码问题
查看>>
Grub的安装方法
查看>>
SpringMVC通过注解方式读取properties文件中的值
查看>>
Spring+Dubbo+Zookeeper简单框架与使用
查看>>
Open Cascade DataExchange DXF
查看>>
Greenplum Hadoop分布式平台大数据解决方案实战教程
查看>>
编译安装LAMP之配置httpd以FastCGI方式与php整合
查看>>
Haproxy
查看>>
性能调优之Java系统级性能监控及优化
查看>>