本文主要是介绍leetcode-Binary Tree Preorder Traversal,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1\2/3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
递归代码如下:
class Solution {
public:vector<int> preorderTraversal(TreeNode* root) {vector<int> res;if(root==NULL) return res;return pre(root,res);}vector<int> pre(TreeNode* root,vector<int>& res){if(root){res.push_back(root->val);pre(root->left,res);pre(root->right,res);}return res;}
};
迭代代码如下:
前序遍历,相当于深度搜索,可用堆栈实现,先进后出,先右后左。参考http://blog.csdn.net/sinat_24520925/article/details/45081749
代码如下:
vector<int> preorderTraversal(TreeNode* root) {vector<int> res;if(root==NULL) return res;stack<TreeNode*> st;st.push(root);while(!st.empty()){TreeNode *p=st.top();st.pop();res.push_back(p->val);if(p->right) st.push(p->right);if(p->left) st.push(p->left);}return res;}
这篇关于leetcode-Binary Tree Preorder Traversal的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!