Leetcode 94 level 0

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?

Answers:

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        std::vector<int> ans;
        inorderTraversal(root,ans);
        return ans;
    }
    void inorderTraversal(TreeNode* root, std::vector<int>& ans) {
        if(!root) return;
        if(root->left!=NULL){
            inorderTraversal(root->left,ans);
        }
        ans.push_back(root->val);
        if(root->right!=NULL){
            inorderTraversal(root->right,ans);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/shit_kingz/article/details/79997197
94