Binary Tree Preorder Traversal

Posted newmoonn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。

题目描述

 

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的主要内容,如果未能解决你的问题,请参考以下文章