144. Binary Tree Preorder Traversal――递归,非递归
2016-03-18 15:39
225 查看
Given a binary tree, return the preorder traversal of its nodes' values.For example:
Given binary tree
return
递归方法:
如果root不为空,
先访问根,递归左子树,递归右子树。
使用栈,迭代方法。
void preorderCore(TreeNode *root,vector<int> &res){
if(!root)
return;
stack<TreeNode*> st;
while(!st.empty()||root){
while(root){
st.push(root);
res.push_back(root->val);
root=root->left;
}
root=st.top();
st.pop();
root=root->right;
}
}
另一种写法为:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,2,3].解法一:
递归方法:
如果root不为空,
先访问根,递归左子树,递归右子树。
void preorderCore(TreeNode *root,vector<int> &res){ if(root){ res.push_back(root->val); preorderCore(root->left,res); preorderCore(root->right,res); } } vector<int> preorderTraversal(TreeNode* root) { vector<int> res; preorderCore(root,res); return res; }解法二:
使用栈,迭代方法。
void preorderCore(TreeNode *root,vector<int> &res){
if(!root)
return;
stack<TreeNode*> st;
while(!st.empty()||root){
while(root){
st.push(root);
res.push_back(root->val);
root=root->left;
}
root=st.top();
st.pop();
root=root->right;
}
}
另一种写法为:
void preorderCore(TreeNode *root,vector<int> &res){ if(!root) return; stack<TreeNode*> st; st.push(root); while(!st.empty()){ root=st.top(); st.pop(); res.push_back(root->val); if(root->right) st.push(root->right); if(root->left) st.push(root->left); } }
相关文章推荐
- HDU 3232 Crossing Rivers [Ad Hoc]
- BZoj 2705: [SDOI2012]Longge的问题【数论】
- 二叉树高度与宽度
- tomcat和maven和sybase的关联
- AndroidStudio上库工程关联
- jetty和udp和tomcat的关联
- linq和tcp和redis的关联
- mac-程序员必备工具(2)-iTerm2
- GetBuffer()函数的使用
- 实现AOP — CGLIB
- svn常用命令
- Android、java环境搭建流程
- Mac下配置Android环境变量
- 被H5逐渐侵蚀的app原生环境
- javascript中的继承
- 【css】IE盒子模型和标准W3C盒子模型
- cmstop中的视图view
- 安卓触摸事件探究
- 用Gvim建立IDE编程环境 (Windows篇)
- 夺命雷公狗---DEDECMS----12dedecms全局标签的使用以及嵌套标签的使用