how to create/implement an algorithm that mirrors a binary tree [closed]

和自甴很熟 提交于 2020-01-03 05:06:50

问题


I'm new to Elixir, and trying to implement an insert/add function to mirror an existing binary tree. Appreciate all ideas.

Don't know where to start.


回答1:


I'm assuming you want to implement a binary tree in Elixir, and that you are also familiar with binary trees. For that, you would need to use a struct (which is just a map behind the scenes).

defmodule TreeNode do
  defstruct value: nil, left: nil, right: nil 

  def new(value), do: %TreeNode{value: value}

  def insert(root = %TreeNode{value: rootValue}, value) when value < rootValue do
    %{root | left: insert(root.left, value)}
  end

  def insert(root = %TreeNode{value: rootValue}, value) when value >= rootValue do
    %{root | right: insert(root.right, value)}
  end

  def insert(nil, value) do
    %TreeNode{value: value}
  end
end

There's no lookup method, which is left as an exercise to you. Usage is pretty simple. Here we create a new tree node which will be the root:

iex(1)> node = TreeNode.new(10)
%TreeNode{left: nil, right: nil, value: 10}

Now we insert 5 into the tree:

iex(2)> node = TreeNode.insert(node, 5)
%TreeNode{
  left: %TreeNode{left: nil, right: nil, value: 5},
  right: nil,
  value: 10
}

And 12:

iex(3)> node = TreeNode.insert(node, 12)
%TreeNode{
  left: %TreeNode{left: nil, right: nil, value: 5},
  right: %TreeNode{left: nil, right: nil, value: 12},
  value: 10
}

And 11:

iex(4)> node = TreeNode.insert(node, 11)
%TreeNode{
  left: %TreeNode{left: nil, right: nil, value: 5},
  right: %TreeNode{
    left: %TreeNode{left: nil, right: nil, value: 11},
    right: nil,
    value: 12
  },
  value: 10
}

With the final shape of the tree resembling the following:

   10
 /    \
5     12
     /
    11

Mirroring now becomes pretty easy. Here's the module that implements the mirroring functionality:

defmodule TreeMirror do
  def mirror(nil), do: nil

  def mirror(node) do
    %TreeNode{value: node.value, left: mirror(node.right), right: mirror(node.left)}
  end
end

To mirror the node we have created earlier above, we simply call TreeMirror.mirror:

iex(5)> mirrored = TreeMirror.mirror node
%TreeNode{
  left: %TreeNode{
    left: nil,
    right: %TreeNode{left: nil, right: nil, value: 11},
    value: 12
  },
  right: %TreeNode{left: nil, right: nil, value: 5},
  value: 10
}

Now the shape of mirrored resembles the following:

   10
 /    \
12     5
  \
  11


来源:https://stackoverflow.com/questions/54724056/how-to-create-implement-an-algorithm-that-mirrors-a-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!