Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

大致题意

给出中序遍历

题解

问题类型:数据结构-树

没什么好说的,中序遍历优先遍历左节点,然后输出中间节点的 val,最后遍历右节点

代码如下

/**
 * 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> result;
        if (root != NULL) this->run(root, result);
        return result;
    }
    
    void run(TreeNode * root, vector<int> & result) {
        if (root->left != NULL) this->run(root->left, result);
        result.push_back(root->val);
        if (root->right != NULL) this->run(root->right, result);
    }
};

sugerPocket
1 声望0 粉丝