[leetcode] Binary Tree Inorder Traversal

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?

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}".
使用非递归的方法中序遍历二叉树。
使用一个栈来模拟递归过程,如果游走指针不为NULL,就把节点入栈,继续访问其左孩子。否则的话访问栈顶元素,并把指针指向他的右孩子。访问栈顶和跳转到右孩子一定要在一个语句块中实现,原因有二,其一为从栈顶弹出的指针的左孩子一定已经访问过了,所以按中序遍历的顺序应该访问该节点,其二这样做就无需判断游走指针指向的节点的左孩子是否访问过,应为栈顶的元素的左孩子一定访问过,只需访问其右孩子即可。
代码如下:
 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 
11 class Solution {
12     public:
13         vector<int> inorderTraversal(TreeNode *root) {
14             vector<int> res;
15             if( root == NULL )
16             {
17                 return res;
18             }
19             TreeNode * tr = root;
20 
21             stack<TreeNode*> s;
22             while(s.size()>0 || tr != NULL)
23             {
24                 if(tr!=NULL)
25                 {
26                     s.push(tr);
27                     tr= tr->left;
28                 }
29                 else
30                 {
31                     tr = s.top();
32                     s.pop();
33                     res.push_back(tr->val);
34                     tr = tr->right;
35                 }
36             }
37             return res;
38         }
39 };

并附上其递归版本:

 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     void T(TreeNode * root,vector<int> & r)
13     {
14         if(root==NULL) return;
15         T(root->left,r);
16         r.push_back(root->val);
17         T(root->right,r);
18     }
19     vector<int> inorderTraversal(TreeNode *root) {
20         // Start typing your C/C++ solution below
21         // DO NOT write int main() function
22         vector<int> r;
23         T(root,r);
24         return r;
25     }
26 };
原文地址:https://www.cnblogs.com/jostree/p/3706341.html