[LeetCode]57. 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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


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}".

 

Subscribe to see which companies asked this question

 

没看明白什么意思。以为是给一个数组{1,#,2,3}作为输入,需要先重建二叉树,然后进行中序遍历,结果给的接口是以TreeNode*为参数;以为是以'#'代替空节点作为终止标识的,结果判断叶子节点还是以NULL为标记。不知前面给这么多example和OJ's Binary Tree Serialization是想说明什么。。。

解法1:非常简单的递归解法

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inOrderTrav(root, res);
        return res;
    }
private:
    void inOrderTrav(TreeNode* root, vector<int>& res)
    {
        if (root == nullptr)
            return;
        if (root->left != nullptr)
            inOrderTrav(root->left, res);
        res.push_back(root->val);
        if (root->right != nullptr)
            inOrderTrav(root->right, res);
    }
};

 

解法2:非递归解法,使用栈作为辅助存储。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> seq;
        TreeNode* curr = root;
        while (curr != nullptr || !seq.empty()) //每颗子树的循环处理
        {
            while (curr != nullptr) //下溯到这颗子树最底层最左边的叶节点
            {
                seq.push(curr);
                curr = curr->left;
            }
            curr = seq.top(); //处理这颗子树最左边的节点
            res.push_back(curr->val);
            seq.pop();
            curr = curr->right; //处理这个子节点的右子树
        }
        return res;
    }
};

 

还有其他的一些二叉树遍历方法,具体参见http://noalgo.info/832.htmlhttp://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html

posted @ 2015-11-05 10:11  AprilCheny  阅读(209)  评论(0编辑  收藏  举报