标签:
先序遍历,用递归来做,简单的不能再简单了。代码如下:
/** * 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 { private: vector<int> res; public: void getOrder(TreeNode* node) { if(node==NULL) return ; else { res.push_back(node->val); getOrder(node->left); getOrder(node->right); } return ; } vector<int> preorderTraversal(TreeNode* root) { if(root==NULL) return res; res.push_back(root->val); getOrder(root->left); getOrder(root->right); return res; } };
但是题目要求用迭代来做。
迭代的代码如下:
/** * 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> res; stack<TreeNode*> stk; while(root!=NULL||!stk.empty()) { if(root!=NULL) { res.push_back(root->val); stk.push(root); root=root->left; } else { root=stk.top()->right; stk.pop(); } } return res; } };
Binary Tree Preorder Traversal
标签:
原文地址:http://www.cnblogs.com/qiaozhoulin/p/4746221.html