首页 > 其他 > 详细

[刷题]LeetCode 144.Binary Tree Preorder Traversal

时间:2020-03-04 16:55:26      阅读:61      评论:0      收藏:0      [点我收藏+]

栈模拟前序遍历

 1 #include <iostream>
 2 #include <vector>
 3 #include <stack>
 4 #include <cassert>
 5 
 6 using namespace std;
 7 
 8 struct TreeNode{
 9     int val;
10     TreeNode* left;
11     TreeNode* right;
12     TreeNode(int x): val(x), left(NULL), right(NULL){}
13 };
14 
15 //模拟指令,go--访问,print--输出    
16 struct Command{
17     string s;
18     TreeNode* node;
19     Command(string s, TreeNode* node):s(s), node(node){}
20 };
21 
22 class Solution{
23     public:
24         vector<int> preorderTraversal(TreeNode* root){
25             vector<int> res;
26             if( root == NULL )
27                 return res;
28             
29             stack<Command> stack;
30             stack.push( Command("go",root) );
31             
32             while( !stack.empty() ){
33                 
34                 Command command = stack.top();
35                 stack.pop();
36                 
37                 if( command.s == "print" )
38                     res.push_back( command.node -> val);
39                 else{
40                     assert( command.s == "go" );
41                     if( command.node -> right )
42                         stack.push( Command("go",command.node->right));
43                     if( command.node -> left)
44                         stack.push( Command("go",command.node->left));
45                     stack.push( Command("print",command.node));
46                 }
47             }
48         }
49 };
50 
51 void print_vec(const vector<int>& vec){
52     for(int e:vec)
53         cout<<e<<" ";
54     cout<<endl;
55 }
56 
57 int main(){
58     TreeNode* root = new TreeNode(1);
59     root->right = new TreeNode(2);
60     root->right->left = new TreeNode(3);
61     vector<int> res = Solution().preorderTraversal(root);
62     print_vec(res);
63     
64     return 0;
65 }

结果:

1-2-3

注意:

  • 模拟了操作系统中方法栈的实现原理
  • 入栈顺序与实际执行顺序相反
  • 本程序可以很容易地改造成栈模拟中序、后序遍历
  • LeetCode 94为中序遍历,145为后序遍历

 

[刷题]LeetCode 144.Binary Tree Preorder Traversal

原文:https://www.cnblogs.com/cxc1357/p/12388632.html

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