首页 > 其他 > 详细

Binary Tree Inorder Traversal

时间:2016-05-23 10:26:08      阅读:126      评论:0      收藏:0      [点我收藏+]

 

 1 /**
 2  * Definition for a binary tree node.
 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> inorderTraversal(TreeNode* root) {
13                vector<int> res;
14                if(root == NULL)
15                         return res;
16                stack<TreeNode *> node;
17                node.push(root);
18                TreeNode *p,*cur;
19                if(root->left != NULL)
20                {
21                        node.push(root->left);
22                        p = root->left;
23                }
24                else
25                {
26                         res.push_back(root->val);
27                         node.pop();
28                         if(root->right != NULL)
29                         {
30                                  node.push(root->right);
31                                  p = root->right;
32                         }
33                         else return res;
34                }
35                while(!node.empty())
36                {
37                         while(p->left != NULL)
38                         {
39                               p = p->left;
40                               node.push(p);
41                         }
42                         cur = node.top();
43                         node.pop();
44                         res.push_back(cur->val);
45                         if(cur->right != NULL)
46                         {
47                               p = cur->right;
48                               node.push(p);
49                         }
50                }
51                return res;
52     }
53 };

 

Binary Tree Inorder Traversal

原文:http://www.cnblogs.com/daocaorenblog/p/5518888.html

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