题目:
Given a binary tree, return the preorder traversal of its nodes‘ values.
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 binary tree * 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> result; result.clear(); if(root == NULL) return result; stack<TreeNode*> right; TreeNode* tmp = root; bool tag = true; while(tag || !right.empty()) { tag = false; while(tmp != NULL) { if(tmp->right != NULL) { right.push(tmp->right); } result.push_back(tmp->val); tmp = tmp->left; } if(!right.empty()) { tag = true; tmp = right.top(); right.pop(); } } return result; } };代码有几个注意点:
class Solution { public: vector<int> preorderTraversal(TreeNode *root) { vector<int> result; stack<TreeNode*> s; if (root) { s.push(root); } while(!s.empty()) { TreeNode* n = s.top(); s.pop(); while(n) { if (n->right) { s.push(n->right); } result.push_back(n->val); n = n->left; } } return result; } };
【LeetCode从零单刷】Binary Tree Preorder Traversal
原文地址:http://blog.csdn.net/ironyoung/article/details/45015127