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

Binary Tree Inorder Traversal

时间:2014-09-13 20:01:35      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   ar   for   div   sp   

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?

confused what "{1,#,2,3}" means?

OJ‘s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.

Here‘s an example:

   1
  /  2   3
    /
   4
         5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
 
 1 /**
 2  * Definition for binary tree
 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         
14         vector<int> result;
15         inOrder(root, result);
16         return result;
17         
18     }
19     
20     void inOrder(TreeNode *root, vector<int> &result)
21     {
22         if(root != NULL)
23         {
24             inOrder(root->left, result);
25             result.push_back(root->val);
26             inOrder(root->right, result);
27         }
28     }
29 };

 

Binary Tree Inorder Traversal

标签:des   style   blog   color   io   ar   for   div   sp   

原文地址:http://www.cnblogs.com/YQCblog/p/3970200.html

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