码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Inorder Traversal

时间:2016-05-23 10:27:52      阅读:120      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!