1. 程式人生 > >Binary Tree Preorder Traversal

Binary Tree Preorder Traversal

binary top tac spa res right pop 遍歷 nod

題目描述

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?

提議:先序遍歷二叉樹,保存結點值到list集合中返回

 1 /**
 2  * Definition for binary tree
3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> preorderTraversal(TreeNode *root) { 13 vector<int> res; 14
stack<TreeNode *> s; 15 if (root == NULL){ 16 return res; 17 } 18 s.push(root); 19 while (!s.empty()){ 20 TreeNode *cur = s.top(); 21 s.pop(); 22 res.push_back(cur->val); 23 if (cur->right!=NULL)
24 s.push(cur->right); 25 if (cur->left!=NULL) 26 s.push(cur->left); 27 } 28 return res; 29 } 30 };

Binary Tree Preorder Traversal