LeetCode 0094 - Binary Tree Inorder Traversal

2021-08-11 10:51:46 浏览数 (1)

Binary Tree Inorder Traversal

Desicription

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

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

代码语言:javascript复制
1
 
  2
 /
3

return [1,3,2].

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

Solution

代码语言:javascript复制
/**
 * 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> res; 
    vector<int> inorderTraversal(TreeNode* root) {
        if(!root)
            return res;
        Traversal(root->left);
        res.push_back(root->val);
        Traversal(root->right);
        return res;
    }
    void Traversal(TreeNode* cur) {
        if(!cur)
            return ;
        Traversal(cur->left);
        res.push_back(cur->val);
        Traversal(cur->right);
    }
};

0 人点赞