LeetCode Binary Tree Preorder Traversal
Problem Description
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?
Problem Solution
递归&非递归方案
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<int> retVec; // the traversal sequence of output public: void recursiveTraverse(TreeNode *root){ if(root == NULL) return; retVec.push_back(root->val); recursiveTraverse(root->left); recursiveTraverse(root->right); } void iterTraverse(TreeNode *root){ if(root==NULL) return; stack<TreeNode*> st; TreeNode* temp; st.push(root); while(!st.empty()) { temp=st.top(); retVec.push_back(temp->val); st.pop(); if(temp->right!=NULL) st.push(temp->right); if(temp->left!=NULL) st.push(temp->left); } } vector<int> preorderTraversal(TreeNode *root) { // recursiveTraverse(root); iterTraverse(root); return retVec; } };
作者:ballwql
本文为作者原创,版权所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。