Binary Tree Inorder Traversal

题目:

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

分析:

Traversal 的方法已经攻克,并无难点。基本题,送分题。

解法:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in vector which contains node values.
     */
public:

    void dfs(TreeNode* root, vector<int>& results) {
        if (root == NULL) {
            return;
        }

        dfs(root->left, results);
        results.push_back(root->val);
        dfs(root->right, results);

    }

    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        if (root == NULL) {
            return vector<int>();
        }
        vector<int> results;
        dfs(root, results);
        return results;
    }
};

results matching ""

    No results matching ""