
二叉树、BST、AVL
love music.
中山大学计算机博士在读,曾就职于腾讯等公司,目前从事AI多模态大模型研究。
展开
-
构建带父结点的二叉树,并输出所有结点到根结点的路径
在构建好二叉树后,需要通过一次遍历来给每个结点的parent赋值,关键代码如下:void triBtee(BTNode *p,BTNode *q)//给各个结点的parent赋值{ if(p == nullptr) return; p->parent = q; q = p; triBtee(p->left,q); triBtee(p->right,q);}...原创 2018-09-27 16:09:45 · 1687 阅读 · 0 评论 -
已知完全二叉树的前序遍历数组,求层次遍历与后序遍历
注意:此种方法仅适用于完全二叉树或满二叉树!!!此种方法仅适用于完全二叉树或满二叉树!!!此种方法仅适用于完全二叉树或满二叉树!!!先根据前序数组得到树的各个结点下标对应的值。例如对于i结点,左子结点是2i,右子结点是2i+1.层次遍历数组:由上已求得tree后序遍历数组:通过后序遍历可得到pos程序代码如下:#include<iostream>using na...原创 2018-09-27 20:28:44 · 2992 阅读 · 1 评论 -
二叉树的遍历(基于栈的非递归方式实现)
原文链接:二叉树的遍历(基于栈的非递归方式实现)二叉树的遍历(基于栈的非递归方式实现)注意:pop的顺序就是对应遍历的打印顺序。在写二叉树的时候如果用递归实现二叉树的遍历很简单,但是用非递归来实现二叉树的遍历就不那么简单了需要一些技巧。那为什么还要非递归实现呢?个人理解:如果树的高度很大,超过了允许递归的次数,那么就会出错,比如我记得python只允许递归100次(不知道记错没)...原创 2018-09-14 15:56:09 · 623 阅读 · 0 评论 -
判断一棵树是否为另一棵树的子树
参考链接:判断一棵树是否为另一棵树的子树思路:1、原二叉树走前序遍历,试图发现哪个节点的值和被判断子树的根节点相同;如果一直到最后也没有找到那么肯定不是2、如果找到了,就两个二叉树一起前序遍历,试图发现两个二叉树同时遍历完成,且同样的左右子树遍历过程中的节点值均相同,同时遍历完成说明有相同的形状,左右子树遍历过程中的节点值均相同说明两个二叉树不仅形状一样,值也是一样,则可以认为是子...原创 2018-10-08 21:20:52 · 1439 阅读 · 1 评论 -
PAT甲级 1064 Complete Binary Search Tree (30 分)完全二叉树、BST
1064 Complete Binary Search Tree (30 分)A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:The left subtree of a node contains only nodes with key...原创 2018-09-23 22:18:18 · 217 阅读 · 0 评论 -
PAT甲级 1094 The Largest Generation (25 分)BFS,树的宽度
1094 The Largest Generation (25 分)A family hierarchy is usually presented by a pedigree tree where all the nodes on the same level belong to the same generation. Your task is to find the generation ...原创 2018-11-09 22:36:59 · 162 阅读 · 0 评论 -
PAT甲级 1102 Invert a Binary Tree (25 分)树的遍历(bfs+dfs)
1102 Invert a Binary Tree (25 分)The following is from Max Howell @twitter:Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so...原创 2018-11-20 18:20:59 · 183 阅读 · 0 评论 -
PAT甲级 1110 Complete Binary Tree (25 分)完全二叉树、dfs
1110 Complete Binary Tree (25 分)Given a tree, you are supposed to tell if it is a complete binary tree.Input Specification:Each input file contains one test case. For each case, the first line g...原创 2018-11-29 10:32:23 · 203 阅读 · 0 评论 -
PAT甲级 1115 Counting Nodes in a BST (30 分)bst
1115 Counting Nodes in a BST (30 分)A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:The left subtree of a node contains only nodes with keys le...原创 2018-11-29 21:14:55 · 194 阅读 · 0 评论