5.3 二叉树的遍历和线索二叉树
5.3.1 二叉树的遍历
先序遍历
void preorder(TreeNode *root, vector<int> &res)
{
if (!root)
{
return;
}
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> res;
preorder(root, res);
return res;
}
中序遍历
void inorder(TreeNode *root, vector<int> &res)
{
if (!root)
{
return;
}
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
};
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> res;
inorder(root, res);
return res;
}
后序遍历
void postorder(TreeNode *root, vector<int> &res)
{
if (!root)
{
return;
}
postorder(root->left, res);
postorder(root->right, res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> res;
postorder(root, res);
return res;
}
层次遍历
队头出队,孩子入队
由遍历序列构造二叉树
由(先序遍历、后序遍历、层次遍历)三选一,加上中序遍历可以唯一确定一棵二叉树。
5.3.2 线索二叉树
加快查找结点前驱和后继的速度。
树 | 森林 | 二叉树 |
---|---|---|
先根遍历 | 先序遍历 | 先序遍历 |
后根遍历 | 中序遍历 | 中序遍历 |