thảo luận Leetcode mỗi ngày

  • Người tạo chủ đề Người tạo chủ đề _Gia_Cat_Luong_
  • Ngày bắt đầu Ngày bắt đầu
Trạng thái
Không mở để trả lời thêm.
Python:
class Solution:
    def tree2str(self, root: Optional[TreeNode]) -> str:
        if root is None: return ""
        if root.left is None and root.right is None: return str(root.val)
        return str(root.val) + "(" + self.tree2str(root.left) +")" + ("" if root.right is None else "(" + self.tree2str(root.right) +")")
 
Nhìn code hơi chán :shame:
Ruby:
def tree2str(root)
  return '' if root.nil?

  left = tree2str(root.left)
  right = tree2str(root.right)
  if right == '' && left != ''
    "#{root.val}(#{left})"
  elsif right == '' && left == ''
    root.val.to_s
  else
    "#{root.val}(#{left})(#{right})"
  end
end
 
Bọn leetcode này bị cuồng cây à
OG0lsXv.png

Mã:
defmodule Solution do
  def tree2str(node, format \\ &no_outer/1) do
    case node do
      %TreeNode{val: v, left: nil, right: nil} ->
        "#{v}" |> format.()

      %TreeNode{val: v, left: l, right: nil} ->
        "#{v}#{tree2str(l, &with_outer/1)}" |> format.()

      %TreeNode{val: v, left: nil, right: r} ->
        "#{v}()#{tree2str(r, &with_outer/1)}" |> format.()

      %TreeNode{val: v, left: l, right: r} ->
        "#{v}#{tree2str(l, &with_outer/1)}#{tree2str(r, &with_outer/1)}" |> format.()
    end
  end

  defp no_outer(s), do: s
  defp with_outer(s), do: "(#{s})"
end
 
Có 15p interview mà ngồi gõ iterative chắc cũng toát mồ hôi :sweat:
u40wsAh.png
tùy công ty nhé

Có công ty nó yêu cầu viết code inorder traversal mà bằng khử đệ quy nhé
FY7e6U1.png
tùy mục đích phỏng vấn là kiểm tra độ nhanh nhạy, não to hay code gọn gàng
 
8LsIshX.png
mà thật ra thì về performance thì iterative sẽ "đa phần" nhanh hơn recursive, như đã thảo luận ở thớt này cách đây mấy ngày

Nhưng ngôn ngữ khác không biết thế nào chứ Java thì cái Generics củ chuối quá
4gmOAMB.png
iterative nhưng cứ allocate rồi free instance trên vùng nhớ heap
 
u40wsAh.png
tùy công ty nhé

Có công ty nó yêu cầu viết code inorder traversal mà bằng khử đệ quy nhé
FY7e6U1.png
tùy mục đích phỏng vấn là kiểm tra độ nhanh nhạy, não to hay code gọn gàng
Công ty làm functional language như Scala, Elixir, ... không kêu chuyển thành loop đâu, bắt viết tail call optimization thôi
hkNtitg.png
 
Python:
class Solution:
    def tree2str(self, root: Optional[TreeNode]) -> str:
        res = []
        def dfs(node):
            res.append(str(node.val))
            if not node.left and not node.right:
                return
            if node.left:
                res.append("(")
                dfs(node.left)
                res.append(")")
            if node.right:
                if not node.left:
                    res.append("()")
                    res.append("(")
                    dfs(node.right)
                    res.append(")")
                else:
                    res.append("(")
                    dfs(node.right)
                    res.append(")")
                    
        dfs(root)
        return "".join(res)
 
8LsIshX.png
mà thật ra thì về performance thì iterative sẽ "đa phần" nhanh hơn recursive, như đã thảo luận ở thớt này cách đây mấy ngày

Nhưng ngôn ngữ khác không biết thế nào chứ Java thì cái Generics củ chuối quá
4gmOAMB.png
iterative nhưng cứ allocate rồi free instance trên vùng nhớ heap
tóm tắt được ko bác, lội 1 hồi mà không thấy đâu có khi bị sót
 
Đa số comment trong link so sánh giữa dùng recursion và iteration đơn thuần không có CTDL hỗ trợ. Kiểu như là factorial bằng recursion VS loop. Những thuật toán recursion mà có thể viết lại kiểu đó thì quá bình thường không có gì đáng nói.

Chứ khi cần sự hỗ trợ của Stack Queue rồi thì so sánh sẽ khác hơn. Bây giờ là hardware stack VS software stack.
 
Bài hôm nay easy. Nhớ hồi đó đề giữa kỳ ctdl auto duyệt cây bằng vòng lặp ^^
Java:
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack=new Stack<>();
        List<Integer> res=new ArrayList<>();
        TreeNode node=root;
        while(node!=null){
            stack.push(node);
            node=node.left;
        }
        while(stack.size()>0){
            node=stack.pop();
            res.add(node.val);
            node=node.right;
            while(node!=null){
                stack.add(node);
                node=node.left;
            }
        }
        return res;
    }
}
 
Python:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        def dfs(node):
            if not node:
                return
            
            dfs(node.left)
            res.append(node.val)
            dfs(node.right)
        dfs(root)
        return res
 
Cho em góp ít lửa bài hôm này :v
PHP:
class Solution {
    /**
     * @param TreeNode $root
     * @return Integer[]
     */
    function inorderTraversal($root) {
        return $root === null ? [] : array_merge($this->inorderTraversal($root->left), [$root->val], $this->inorderTraversal($root->right));
    }
}
 
Lại inorder ah :go:
Hqua dùng Recursion rồi thì hnay dùng Iteration vầy
Ruby:
def inorder_traversal(root)
  stack = []
  curr = root
  res = []
  until curr.nil? && stack.empty?
    while curr
      stack << curr
      curr = curr.left
    end
    curr = stack.pop
    res << curr.val
    curr = curr.right
  end
  res
end
 
soành điệu xài std::variant
uq1dgnk.png


C++:
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<variant<TreeNode*, int>> st;
        st.emplace(root);
        while (!st.empty()) {
            auto v = move(st.top());
            st.pop();
            visit(overloaded{
                [&](int val) { res.push_back(val); },
                [&](TreeNode* p) {
                    if (p == nullptr) return;
                    st.emplace(p->right);
                    st.emplace(p->val);
                    st.emplace(p->left);
                }
            }, v);
        }
        return res;
    }
};
 
FfsqRRV.png
Recursive approach is.......à mà thôi
Q8sGcLO.png
nay làm recursive lẫn iterative luôn

Java:
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        inorder(root, ans);
        return ans;
    }
    void inorder(TreeNode root, List<Integer> nums)
    {
        if(root == null)
        {
            return;
        }
        inorder(root.left, nums);
        nums.add(root.val);
        inorder(root.right, nums);
    }
}
 
Trạng thái
Không mở để trả lời thêm.

Thống kê chủ đề

Ngày tạo
_Gia_Cat_Luong_,
Người trả lời cuối
Vipluckystar,
Trả lời
17.755
Lượt xem
1.212.996
Quay lại
Lên đầu trang