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

LeetCode OJ:Binary Tree Inorder Traversal(中序遍历二叉树)

时间:2015-10-26 20:36:30      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return the inorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1
         2
    /
   3

 

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?
中序遍历二叉树,递归遍历当然很容易,题目还要求不用递归,下面给出两种方法:

递归:

 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         if(!root) return ret;
14         tranverse(root);
15         return ret;
16     }
17 
18     void tranverse(TreeNode * root)
19     {
20         if(!root) return;
21         tranverse(root->left);
22         ret.push_back(root->val);
23         tranverse(root->right);
24     }
25 private:
26     vector<int> ret;
27 };

迭代:

 1 class Solution {
 2 public:
 3     vector<int> inorderTraversal(TreeNode* root) {
 4         vector<int> ret;
 5         if(!root) return ret;
 6         map<TreeNode *, bool> m;
 7         stack<TreeNode *> s;
 8         s.push(root);
 9         while(!s.empty()){
10             TreeNode * t = s.top();
11             if(t->left && !m[t->left]){
12                 m[t->left] = true;
13                 s.push(t->left);
14                 t = t->left;
15                 continue;
16             }
17             ret.push_back(t->val);
18             s.pop();
19             if(t->right && !m[t->right]){
20                 m[t->right] = true;
21                 s.push(t->right);
22                 t = t->right;
23             }
24         }
25         return ret;
26     }
27 };

 

LeetCode OJ:Binary Tree Inorder Traversal(中序遍历二叉树)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4912136.html

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