Lintcode 二叉树的前序遍历
来源:互联网 发布:fifo和lifo存货的算法 编辑:程序博客网 时间:2024/05/18 02:26
1.描述
给出一颗二叉树,返回其节点值的前序遍历。
样例
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,2,3]
.
2.分析
如图,每读到一个节点的值加入到vector中,之后要进行操作的节点变为当前节点的左孩子(root->left),
一直走到左孩子为空转而操作父亲节点的右孩子,之后是再上一个父亲节点,通过递归实现。
3.代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
void pre(vector<int> &v,TreeNode *root)
{
if(root==NULL) return;
else
{
v.push_back(root->val);
pre(v,root->left);
pre(v,root->right);
}
}
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
pre(v,root);
return v;
}
};
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
void pre(vector<int> &v,TreeNode *root)
{
if(root==NULL) return;
else
{
v.push_back(root->val);
pre(v,root->left);
pre(v,root->right);
}
}
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
pre(v,root);
return v;
}
};
4.总结
注意判断递归函数结束的标志,if(root==NULL) return;当前操作的节点为空,说明他的
父亲节点为叶子节点,转而对父亲节点的右子树进行操作,右子树操作也完成后退回父亲
节点的右子树,层层递归。
0 0
- LintCode -- 二叉树的前序遍历
- lintcode 二叉树的前序遍历
- lintcode,二叉树的前序遍历
- LintCode-二叉树的前序遍历
- lintcode 二叉树的前序遍历
- LintCode 二叉树的前序遍历
- lintcode二叉树的前序遍历
- 二叉树的前序遍历-LintCode
- Lintcode 二叉树的前序遍历
- lintcode--二叉树的前序遍历
- lintcode:二叉树的前序遍历
- lintcode-二叉树的前序遍历(非递归)-66
- LintCode之二叉树的前序遍历
- Lintcode 66 二叉树的前序遍历
- LintCode | 66. 二叉树的前序遍历
- lintcode——二叉树的前序遍历
- lintcode 66 二叉树的前序遍历
- LintCode 66 二叉树的前序遍历
- 关于javax.validation.Validator校验的使用
- json的另外一种写法
- nginx端口占用,启动报错:bind() to 0.0.0.0:80 failed (10013: An attempt was made to access a socket in a way f
- qt 类型装换
- 【转载】从Fiddler抓包到Jmeter接口测试(简单的思路)
- Lintcode 二叉树的前序遍历
- 图片标注工具LabelImg使用教程
- 连接
- IOS 教程:自定义链接下载应用并直接安装ipa-itms-services
- 综合里dont_use/dont_touch/ideal_network的理解
- JAVA变量,数据类型及转换,
- 子树
- 遍历字符串
- 分析Ajax请求抓取今日头条街拍美图