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

leetcode 94. Binary Tree Inorder Traversal

时间:2015-01-18 11:45:40      阅读:173      评论: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].

inorder, 即按照“左根右”的顺序遍历,

1、当前访问节点不为空,则一直向左遍历,当前节点压栈

2、否则,取栈顶节点访问之,并遍历右节点

 1 vector<int> inorderTraversal(TreeNode *root) 
 2     {
 3         vector<int> tree_nodes;
 4         stack<TreeNode*> stree;
 5         TreeNode* visit = root;
 6         
 7         while (!stree.empty() || (visit != NULL))
 8         {
 9             if (visit != NULL)      // if visit is not empty, push it into stack and visit left
10             {
11                 stree.push(visit);
12                 visit = visit->left;
13             }
14             else    // visit is null, get top node from stack, visit it, and put visit to right
15             {
16                 visit = stree.top();
17                 stree.pop();
18                 tree_nodes.push_back(visit->val);
19                 visit = visit->right;
20             }
21         }
22         
23         return tree_nodes;
24     }

 

leetcode 94. Binary Tree Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4231546.html

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