Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@ryujignh

InOrder Traversal

More than 1 year has passed since last update.

require 'test/unit'
require 'pry'
class InOrderTraversal < Test::Unit::TestCase

  def test_run

    input = [1, nil, 2, 3]

    tree = TreeNode.new(1)
    tree.left = TreeNode.new(nil)
    tree.right = TreeNode.new(2)
    tree.right.left = TreeNode.new(3)
    assert_equal([1, 3, 2],
                 inorder_traversal(tree))

    assert_equal([],
                 inorder_traversal(nil))
  end

  def inorder_traversal(root, result = [])
    if root == nil || root.val.nil?
      return []
    end

    inorder_traversal(root.left, result) if root.left
    result << root.val
    inorder_traversal(root.right, result) if root.right
    result
  end

end


# Definition for a binary tree node.
class TreeNode
  attr_accessor :val, :left, :right

  def initialize(val)
    @val = val
    @left, @right = nil, nil
  end
end
0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?