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?
Answer 1: 递归法
思路:如果当前节点不为空,先把当前节点的值放入数组。从树的根结点开始,再先序遍历左子树和右子树,最后返回数组。迭代终止条件,如果当前节点为空,则返回数组。
AC Code:
/** * 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) { if(root == NULL) return Vpreorder; Vpreorder.push_back(root->val); preorderTraversal(root->left); preorderTraversal(root->right); return Vpreorder; } private: vector<int> Vpreorder; };
Answer 2: 非递归法
思路:使用栈的非递归算法。先用根结点初始化栈,然后在栈不为空时,循环做以下操作,然后访问栈顶节点,接下来依次把栈顶节点的右结点和栈顶节点的左结点压栈(注意次序 ,先右结点,后左结点,一定不能反),因为先序遍历是先访问左子树,后访问右子树。
AC Code:
/** * 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> ret; if(root == NULL) return ret; stack<TreeNode*> stk; stk.push(root); while(!stk.empty()) { TreeNode* node = stk.top(); stk.pop(); ret.push_back(node->val); //次序不能反,一定要先压入右结点,再压入左结点 if(node->right) stk.push(node->right); if(node->left) stk.push(node->left); } return ret; } };
[C++]LeetCode: 95 Binary Tree Preorder Traversal (先序遍历)
原文地址:http://blog.csdn.net/cinderella_niu/article/details/42714691