简体   繁体   English

接受二叉树并返回总和的函数

[英]Function that takes a binary tree and returns the sum

I'm new in to elixir and i have question that i'm stack in 我是不老长生不老药,我有一个问题,我在里面

a binary tree 一棵二叉树

Implement a function, sum/1 , that takes a binary tree and returns the sum of all values in the tree. 实现一个函数sum/1 ,该函数采用一棵二叉树并返回树中所有值的和。 The tree is represented as follows: 该树表示如下:

 @type tree :: {:node, integer(), tree(), tree()} | nil

An example of a depth-wise tree walk in elixir that takes a function to be executed on each node is at https://gist.github.com/kipcole9/43f9551e3c579a7d33e8daed10359c2c https://gist.github.com/kipcole9/43f9551e3c579a7d33e8daed10359c2c中包含需要在每个节点上执行的功能的elixir中的深度树遍历示例

Basically separate the problem into two parts: 基本上将问题分为两部分:

  1. Walk the tree recursively 递归地走树

  2. Apply a given function to act on the current node's value, the result of executing the function on the left branch and the result of executing the function on the right branch 将给定函数应用于当前节点的值,在左分支上执行该函数的结果,在右分支上执行该函数的结果

     defmodule Treewalk do @type tree :: {:node, integer(), tree(), tree()} | nil def depth({:node, value, nil, nil}, _fun) do value end def depth({:node, value, nil, right}, fun) do fun.(value, depth(right, fun), nil) end def depth({:node, value, left, nil}, fun) do fun.(value, depth(left, fun), nil) end def depth({:node, value, left, right}, fun) do fun.(value, depth(left, fun), depth(right, fun)) end # The function to be run on each # node of the tree which is passed # the current value, the result of # running the funciton on the left # branch and the result of running # the function on the right branch def adder(a, b, nil) do a + b end def adder(a, b, c) do a + b + c end # Test tess def tree do {:node, 1, {:node, 2, {:node, 4, nil, nil}, nil }, {:node, 3, nil, {:node, 4, nil, nil} } } end def sum(tree) do depth(tree, &adder/3) end # run a test, returns 14 def test do depth(tree(), &adder/3) end end 

Try this. 尝试这个。

@type tree :: {:node, integer(), tree(), tree()} | nil

def sum(nil), do: 0

def sum({:node, int, l, r}) do

  int + sum(l) + sum(r)

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM