← Static tasks

94. Binary Tree Inorder Traversal

leetcode easy

#csharp#easy#leetcode#recursion#tree#two-pointers

Task

Дан корень бинарного дерева. Верните обход значений его узлов в симметричном порядке.

Пример:

Input: root = [1,null,2,3]

Output: [1,3,2]

C# solution

matched/original
public class Solution {
    List<int> res = new List<int>();
    public IList<int> InorderTraversal(TreeNode root) {
        Helper(root);
        return res;
    }
    public void Helper(TreeNode root) {
        if (root != null) {
            Helper(root.left);
            res.Add(root.val);
            Helper(root.right);
        }
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    List<int> res = new List<int>();
    public vector<int> InorderTraversal(TreeNode root) {
        Helper(root);
        return res;
    }
    public void Helper(TreeNode root) {
        if (root != null) {
            Helper(root.left);
            res.push_back(root.val);
            Helper(root.right);
        }
    }
}

Java solution

matched/original
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root, res);
        return res;
    }

    public void helper(TreeNode root, List<Integer> res) {
        if (root != null) {
            helper(root.left, res);
            res.add(root.val);
            helper(root.right, res);
        }
    }
}

JavaScript solution

matched/original
var inorderTraversal = function (root) {
    let res = [];
    helper(root, res);
    return res;
};
var helper = function (root, res) {
    if (root !== null) {
        helper(root.left, res);
        res.push(root.val);
        helper(root.right, res);
    }
};

Explanation

Algorithm

Метод решения этой задачи использует рекурсию. Это классический метод, и он простой. Мы можем определить вспомогательную функцию для реализации рекурсии.

😎