3.1 分别用递归和非递归方式实现二叉树先序、中序和后序遍历
(LeetCode 144)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Recursive
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(root){
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return res;
}
vector<int> res;
};
//iterative
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root)return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* cur=st.top();
st.pop();
res.push_back(cur->val);
if(cur->right)st.push(cur->right);
if(cur->left)st.push(cur->left);
}
return res;
}
};
3.2 打印二叉树的边界节点
3.3 如何较为直观地打印二叉树
3.4 二叉树的序列化和反序列化
3.5 遍历二叉树的神级方法
3.6 在二叉树中找到累加和为指定值的最长路径长度
3.7 找到二叉树中符合搜索二叉树条件的最大拓扑结构
3.8 二叉树按层打印与zigzag打印
3.9 调整二叉树中两个错误的节点
3.10 判断t1树中是否包含t2树全部的拓扑结构
3.11 判断t1树中是否有与t2树拓扑结构完全相同的子树
3.12 判断二叉树是否为平衡二叉树
3.13 根据后序数组重建搜索二叉树
3.14 判断一棵二叉树是否为搜索二叉树和完全二叉树
3.15 通过有序数组生成平衡搜索二叉树
3.16 在二叉树中找到一个节点的后继节点
3.17 在二叉树中找到两个节点的最近公共祖先
3.18 Tarjan算法与并查集解决二叉树节点间最近公共祖先的批量查询问题
3.19 二叉树节点间的最大距离问题
3.20 先序、中序和后序数组两两结合重构二叉树
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size()==0)return NULL;
TreeNode* res=func(pre,vin,0,pre.size()-1,0,vin.size()-1);
return res;
}
TreeNode* func(vector<int> &pre,vector<int> &in,int preleft, int preright,int inleft,int inright){
if(preleft>preright || inleft>inright)return NULL;
int val=pre[preleft],inroot;
for(int i=inleft;i<=inright;i++){
if (in[i]==val){
inroot=i;
break;
}
}
TreeNode* root=new TreeNode(val);
root->left=func(pre,in,preleft+1,inroot-inleft+preleft,inleft,inroot-1);
root->right=func(pre,in,inroot-inleft+preleft+1,preright,inroot+1,inright);
return root;
}
};
3.21 通过先序和中序数组生成后序数组
3.22 统计和生成所有不同的二叉树
3.23 统计完全二叉树的节点数