现在的位置: 首页 > 综合 > 正文

LeetCode题解:Binary Tree Inorder Traversal

2019年07月24日 ⁄ 综合 ⁄ 共 1000字 ⁄ 字号 评论关闭

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?

思路:

对每个node做一个记号。第一次碰到的时候,先进入其左子树。第二次碰到的时候,访问该结点。

题解:

/**
 * 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) {
        if (root == nullptr)
            return vector<int>();
        
        vector<int> result;
            
        // the bool states if its left leaf is visited already
        list<pair<TreeNode*, bool>> nodes;
        nodes.push_back(make_pair(root, false));
        while(!nodes.empty())
        {
            auto& front = nodes.front();
            if (front.second == false)
            {
                // its left node has not visited
                front.second = true;
                
                if (front.first->right != nullptr)
                    nodes.insert(next(begin(nodes)), make_pair(front.first->right, false));
                if (front.first->left != nullptr)
                    nodes.push_front(make_pair(front.first->left, false));
                continue;
            }
            else
            {
                result.push_back(front.first->val);
                nodes.pop_front();
            }
        }
        
        return result;
    }
};

抱歉!评论已关闭.