[Leetcode][Tree][Binary Tree Inorder Traversal]

二叉树的中序遍历

 

1、递归版本

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

总结:又CE了一次。。。囧~

太久不写程序,总是有一些细节错误。

  

2、迭代版本

/**
 * Definition for binary tree
 * 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> result;
        stack<TreeNode*> s;
        TreeNode *now = root;
        while (now != NULL || !s.empty()) {
            if (now != NULL) {
                s.push(now);
                now = now->left;
            } else {
                now = s.top();
                s.pop();
                result.push_back(now->val);
                now = now->right;
            }
            
        }
        return result;
    }
};

  

总结:

CE一次,把push写成了push_back;

TLE一次,首先把左儿子节点都压入栈,等左子树都访问完之后,再输出自己,然后再访问右子树。

AC,加了一个另外的条件:当前结点是否为null。

关键是如何保证top点的左子树已经被完全访问。

 

posted @ 2014-06-28 13:01  poemqiong  阅读(141)  评论(0编辑  收藏  举报