1. what is binary tree
a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.
二叉树的第i层至多拥有2^i-1个节点;
满二叉树(Full Binary Tree):一棵深度为k,且有 2^(k+1)-1 个节点的二叉树。这种树的特点是每一层上的节点数都是最大节点数。
完全二叉树(Complete Binary Tree):除最后一层外,若其余层都是满的,并且最后一层或者是满的,或者是在右边缺少连续若干节点。具有n个节点的完全二叉树的深度为log2(n+1)。深度为k的完全二叉树,至少有 2^k个节点,至多有2^(k+1)-1个节点。
2.存储结构
- 顺序存储:虽然在遍历速度上有一定的优势,但因所占空间比较大,是非主流二叉树。二叉树通常以链式存储。
#define LENGTH 100
typedef char datatype;
typedef struct node{
datatype data;
int lchild,rchild;
int parent;
}Node;
Node tree[LENGTH];
int length;
int root;
- 链式存储:
typedef char datatype;
typedef struct BinNode{
datatype data;
struct BinNode* lchild;
struct BinNode* rchild;
}BinNode;
typedef BinNode* bintree; //bintree本身是个指向结点的指针
3. Tree traversal 树的遍历
对于二叉树,有深度遍历和广度遍历。
深度遍历有前序、中序以及后序三种遍历方法。
广度遍历即我们平常所说的层次遍历。
因为树的定义本身就是递归定义,因此采用递归的方法去实现树的三种遍历不仅容易理解而且代码很简洁,而对于广度遍历来说,需要其他数据结构的支撑,比如堆了。
四种主要的遍历思想为:
前序遍历:根结点 ---> 左子树 ---> 右子树
中序遍历:左子树---> 根结点 ---> 右子树
后序遍历:左子树 ---> 右子树 ---> 根结点
层次遍历:只需按层次遍历即可
4. 验证二叉搜索树(98)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* prev = NULL;
return validate(root, prev);
}
bool validate(TreeNode* node, TreeNode* &prev) {
if (node == NULL) return true;
if (!validate(node->left, prev)) return false;
if (prev != NULL && prev->val >= node->val) return false;
prev = node;
return validate(node->right, prev);
}
};
5. 二叉树层次遍历102
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (root == NULL) return res;
queue<pair<TreeNode*, int>> q;
q.push(make_pair(root, 0));
vector<int> level;
int currentlevel=0;
while (!q.empty()) {
auto p=q.front(); q.pop();
if (p.second == currentlevel) level.push_back(p.first->val);
else {
res.push_back(level);
level.clear();
level.push_back(p.first->val);
currentlevel = p.second;
}
if (p.first->left) q.push(make_pair(p.first->left, currentlevel+1));
if (p.first->right) q.push(make_pair(p.first->right, currentlevel+1));
}
res.push_back(level);
return res;
}
};
6. 二叉树层次遍历107
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
protected:
vector<vector<int>> ans;
void dfs(TreeNode *root, int height){
if (root == NULL)
return;
while (ans.size() <= height)
ans.push_back(vector<int>());
ans[height].push_back(root->val);
dfs(root->left, height + 1);
dfs(root->right, height + 1);
}
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
dfs(root, 0);
reverse(ans.begin(), ans.end());
return ans;
}
};
参考链接:
1.二叉树