二叉树的前序、中序、后序遍历
来源:互联网 发布:vscode 编码方式默认 编辑:程序博客网 时间:2024/05/18 22:53
问题描述:给出一棵二叉树返回其节点值得前序遍历
解题思路:写一个递归函数,将每一次遍历的节点放在vector里,前序中序后序遍历完成后,将vector里的值输出即可
实现代码:class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> vec;
first(vec,root);
return vec;
}
void first(vector<int> &vec,TreeNode *root){
if(root==NULL) return;
else
{
vec.push_back(root->val);
first(vec,root->left);
first(vec,root->right);
}
}
};
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
vector<int> vec;
second(vec,root);
return vec;
}
void second(vector<int> &vec,TreeNode *root){
if(root==NULL) return;
else
{
second(vec,root->left);
vec.push_back(root->val);
second(vec,root->right);
}
}
};
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> vec;
third(vec,root);
return vec;
}
void third(vector<int> &vec,TreeNode *root)
{ if(root==NULL) return;
else{
third(vec,root->left);
third(vec,root->right);
vec.push_back(root->val);
}
}
};
感悟:递归很好想,就是你得想法把遍历的节点怎么输出,数组输出就行了,不同位置的输出对应不同的便利,改一下输出的位置就好了。
- 二叉树的前序、中序、后序遍历
- 二叉树的遍历(前序,中序,后序)
- 二叉树的遍历:前序、中序、后序
- 二叉树的前序、中序、后序遍历
- 二叉树的前序、中序、后序遍历
- 二叉树的前序,中序,后序遍历
- 二叉树的前序、中序、后序遍历
- 二叉树的前序,中序,后序遍历
- 二叉树的前序、中序、后序遍历
- 二叉树的前序、中序、后序遍历
- 二叉树的前序、中序、后序遍历
- 二叉树的前序,中序,后序遍历
- 二叉树的前序,中序,后序遍历
- 二叉树的前序、中序、后序遍历
- 二叉树的前/中/后序遍历
- JAVA实现二叉树的前、中、后序遍历
- 二叉树的前、中、后序遍历详解
- 二叉树的前、中、后序遍历
- 打印数据库查询结果ResultSet
- Windows安装Rtools
- 103 Docker基础原理
- Java中的装箱与拆箱
- JAVA OOP 第八章JDBC练习+Basedao
- 二叉树的前序、中序、后序遍历
- Android Studio 如何修改应用程序的版本号targetSdkVersion和Application Id
- IMWeb训练营第一天
- Yaf学习笔记之钩子与插件
- vlc
- 使用pandas读取csv文件指定的前几行
- JDK1.7源码笔记之Arrays类
- 关于HTML的学习
- 剪邮票