题目 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. Input Specification: Each input file contains one t…
7-4 Cartesian Tree (30分)   A Cartesian tree is a binary tree constructed from a sequence of distinct numbers. The tree is heap-ordered, and an inorder traversal returns the original sequence. For example, given the sequence { 8, 15, 3, 4, 1, 5, 12, 1…
给定先序中序遍历的序列,可以确定一颗唯一的树 先序遍历第一个遍历到的是根,中序遍历确定左右子树 查结点a和结点b的最近公共祖先,简单lca思路: 1.如果a和b分别在当前根的左右子树,当前的根就是最近祖先 2.如果根等于a或者根等于b了,根就是最近祖先:判断和a等还是和b等就行了 3.如果都在左子树上,递归查左子树就可以了.这里找到左子树的边界和根(通过先序中序序列) 4.如果都在右子树上,递归查右子树. 代码1:不建树的做法,参考柳婼blog~ #include<bits/stdc++.h>…
http://poj.org/problem?id=3694 这一题  为什么要找最小祖先呢 当两个节点连到一块的时候  找最小公共节点就相当于找强连通分支 再找最小公共节点的过程中直到找到  这个过程中所有的点就是一个强连通分支 现在要求桥   只需用没有加边的时候的桥数减去后来找到的强连通分支里的桥数就得到加边后的桥数 Network Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 7720   Accepted: 2…
题意: 输入一个正整数N(<=20),代表结点个数(0~N-1),接着输入N行每行包括每个结点的左右子结点,'-'表示无该子结点,输出是否是一颗完全二叉树,是的话输出最后一个子结点否则输出根节点. trick: 用char输入子结点没有考虑两位数的结点…
题面 题解 我们求它子树的权值和,一般用dfs序把树拍到线段树上做. 当它换根时,我们就直接把root赋值就行了,树的结构不去动它. 对于第二个操作,我们得到的链和根的相对位置有三种情况: 设两点为A.B,LCA 为 C,一个点x的dfs序为ld[x],从它的子树里出来时的dfs序为rd[x] 第一种情况,根是C的祖先,他的实际操作区间就是原本的子树区间[ld[C],rd[C]] 第二种情况,根在A.B路径上,那么它的实际LCA就应该是root,操作区间为[1,n] 第三种情况,根在C的子树上,…
Source: PAT A1151 LCA in a Binary Tree (30 分) Description: The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their…
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. Input Specification: Each input file contains one test…
题目描述 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.Given any two nodes in a binary tree, you are supposed to find their LCA. 最小共同祖先(LCA)是一棵树中两个节点U和V最深的那个公共父节点.要求给一棵树,以及两个节点,请你…
1151 LCA in a Binary Tree (30 分) The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. Given any two nodes in a binary tree, you are supposed to find their LCA. Input Specification:…