LeetCode144: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?
解题思路:
利用栈实现,很简单的一题,不多说了,直接上代码
实现代码:
#include <iostream> #include <vector> #include <stack> using namespace std; /** Given a binary tree, return the preorder traversal of its nodes' values. */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void addNode(TreeNode* &root, int val) { if(root == NULL) { TreeNode *node = new TreeNode(val); root = node; } else if(root->val < val) { addNode(root->right, val); } else if(root->val > val) { addNode(root->left, val); } } void printTree(TreeNode *root) { if(root) { cout<<root->val<<" "; printTree(root->left); printTree(root->right); } } class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> ivec; if(root) { stack<TreeNode *> tstack; TreeNode *p = root; while(p || !tstack.empty()) { while(p) { ivec.push_back(p->val); tstack.push(p); p = p->left; } if(!tstack.empty()) { TreeNode *t = tstack.top(); tstack.pop(); p = t->right; } } } return ivec; } }; int main(void) { TreeNode *root = new TreeNode(5); addNode(root, 7); addNode(root, 3); addNode(root, 15); addNode(root, 1); printTree(root); cout<<endl; Solution solution; vector<int> v = solution.preorderTraversal(root); vector<int>::iterator iter; for(iter = v.begin(); iter != v.end(); ++iter) cout<<*iter<<" "; cout<<endl; return 0; }
-----------------------我和我追猪的梦-----------------------------------------------------------------
作者:mickole