首页 > 其他 > 详细

Binary Tree Preorder Traversal

时间:2018-04-08 23:09:57      阅读:174      评论:0      收藏:0      [点我收藏+]

题目描述

 

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

原文:https://www.cnblogs.com/cwfzzz/p/8747974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!