144. Binary Tree Preorder Traversal
题目:
Given a binary tree, return the preorder traversal of its nodes' values.
思路:
二叉树的前序遍历一般分为递归和非递归两种,非递归通过栈来存储节点。
代码:
递归:
1 class Solution { 2 public: 3 vector<int> preorderTraversal(TreeNode* root) { 4 vector<int> result; 5 preorder(result, root); 6 return result; 7 } 8 9 void preorder(vector<int>& result, TreeNode *root) { 10 if (root == NULL) 11 return; 12 result.push_back(root->val); 13 if (root->left != NULL) 14 preorder(result, root->left); 15 if (root->right != NULL) 16 preorder(result, root->right); 17 } 18 };
循环:
1 class Solution { 2 public: 3 vector<int> preorderTraversal(TreeNode* root) { 4 vector<int> result; 5 if (root == NULL) 6 return result; 7 8 stack<TreeNode*> s; 9 s.push(root); 10 11 while (!s.empty()) { 12 TreeNode *temp = s.top(); 13 s.pop(); 14 result.push_back(temp->val); 15 if (temp->right != NULL) 16 s.push(temp->right); 17 if (temp->left != NULL) 18 s.push(temp->left); 19 20 } 21 return result; 22 } 23 24 };