标签:
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?
题目描述:
这是一个二叉树的先序遍历的题目,思路是直接用栈去实现。具体代码是借鉴的别人的,没怎么看懂,先把代码附上,以后慢慢体会。
代码实现:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int>re; const TreeNode *p; stack<const TreeNode *>s; p=root; if(p!=NULL) { s.push(p); } while(!s.empty()) { p=s.top(); s.pop(); re.push_back(p->val); if(p->right!=NULL) { s.push(p->right); } if(p->left!=NULL) { s.push(p->left); } } return re; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetcode: Binary Tree Preorder Traversal
标签:
原文地址:http://blog.csdn.net/flyljg/article/details/48006391