![](/img/trans.png)
[英]Write a function that takes in a tree and returns the maximum sum of the values along any path in the tree
[英]Function that takes a binary tree and returns the sum
我是不老長生不老葯,我有一個問題,我在里面
一棵二叉樹
實現一個函數sum/1
,該函數采用一棵二叉樹並返回樹中所有值的和。 該樹表示如下:
@type tree :: {:node, integer(), tree(), tree()} | nil
https://gist.github.com/kipcole9/43f9551e3c579a7d33e8daed10359c2c中包含需要在每個節點上執行的功能的elixir中的深度樹遍歷示例
基本上將問題分為兩部分:
遞歸地走樹
將給定函數應用於當前節點的值,在左分支上執行該函數的結果,在右分支上執行該函數的結果
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
嘗試這個。
@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.