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

二叉树的中序遍历

时间:2017-05-02 19:43:22      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:www   blank   data   param   contain   非递归   active   return   tags   

二叉树的中序遍历 

给出一棵二叉树,返回其中序遍历

样例

给出二叉树 {1,#,2,3},

   1
         2
    /
   3

返回 [1,3,2].

挑战 

你能使用非递归算法来实现么?

标签 
 
 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14     /**
15      * @param root: The root of binary tree.
16      * @return: Inorder in vector which contains node values.
17      */
18 public:
19     vector<int> inorderTraversal(TreeNode *root) {
20         // write your code here
21         vector<int> order;
22         if(root == NULL)
23             return order;
24 
25         stack<TreeNode*> s;
26         TreeNode *p=root;
27         while(p!=NULL||!s.empty()) {
28             while(p!=NULL) {
29                 s.push(p);
30                 p=p->left;
31             }
32             if(!s.empty()) {
33                 p=s.top();
34                 order.push_back(p->val);
35                 s.pop();
36                 p=p->right;
37             }
38         } 
39         return order;
40     }
41 };

 

二叉树的中序遍历

标签:www   blank   data   param   contain   非递归   active   return   tags   

原文地址:http://www.cnblogs.com/libaoquan/p/6797500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!