传送门 Description Binary trees can sometimes be very difficult to work with. Fortunately, there is a class of trees with some really nice properties. A rooted binary tree is called “nice”, if every node is either a leaf, or has exactly two children. Fo…
把二叉搜索树转换为累加树 描述 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和. 例如: 输入: 二叉搜索树: 5 / \ 2 13 输出: 转换为累加树: 18 / \ 20 13 解析 标准中序遍历,再反着遍历,每个节点的值 += 前一个节点的值. 代码 傻方法 先把树,左右全部交换,再标准中序遍历,再左右交换回来. public TreeNode convertBST(Tr…
interlinkage: https://jzoj.net/senior/#contest/show/2703/1 description: solution: 发现$dfs$序不好维护 注意到这是一棵平衡树,左旋右旋中序遍历不会改变,且一个点的子树在中序遍历上也是一个连续的区间 每次旋转只改变两个点的力量值 在中序遍历上建线段树维护单点修改,区间乘积查询就好 code: #include<algorithm> #include<cstring> #include<iost…
3173: [Tjoi2013]最长上升子序列 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 1183  Solved: 610[Submit][Status][Discuss] Description 给定一个序列,初始为空.现在我们将1到N的数字插入到序列中,每次将一个数字插入到一个特定的位置.每插入一个数字,我们都想知道此时最长上升子序列长度是多少? Input 第一行一个整数N,表示我们要将1到N插入序列中,接下是N个数字,第k个数字Xk…
给定先序中序遍历的序列,可以确定一颗唯一的树 先序遍历第一个遍历到的是根,中序遍历确定左右子树 查结点a和结点b的最近公共祖先,简单lca思路: 1.如果a和b分别在当前根的左右子树,当前的根就是最近祖先 2.如果根等于a或者根等于b了,根就是最近祖先:判断和a等还是和b等就行了 3.如果都在左子树上,递归查左子树就可以了.这里找到左子树的边界和根(通过先序中序序列) 4.如果都在右子树上,递归查右子树. 代码1:不建树的做法,参考柳婼blog~ #include<bits/stdc++.h>…
紫书:P155 uva  548   You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that pa…
二叉查找树通俗说就是左孩子比父亲小,右孩子比父亲大.构造这么一个树,树嘛,递归即可. 例如一棵树后序遍历是这样(下图的树):2 9 8 16 15 10 25 38 45 42 30 20.最后的20肯定是树根,这里要抓住一个规律:20是树根,那么2 9 8 16 15 10都是左子树,25 38 42 45 30在右子树,因为左边都小于根.右边都大于根嘛.然后递归即可. 下面是树的样子和代码和src.txt(后序遍历的结果)以及运行结果: #include <iostream> #inclu…
一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点, 其左子树中所有结点的键值小于该结点的键值: 其右子树中所有结点的键值大于等于该结点的键值: 其左右子树都是二叉搜索树. 所谓二叉搜索树的"镜像",即将所有结点的左右子树对换位置后所得到的树. 给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果. 输入格式: 输入的第一行给出正整数N(<=1000).随后一行给出N个整数键值,其间以空格分隔. 输出格式: 如果输入序列是对一…
题目: Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 思路: 按照树的先序遍历顺序把节点串联起来即可. /** * Definition for a binary tree node. * function TreeNode(va…
03-树1. List Leaves (25) Given a tree, you are supposed to list all the leaves in the order of top down, and left to right. Input Specification: Each input file contains one test case. For each case, the first line gives a positive integer N (<=10) wh…