我想从二叉搜索树的根中找到一条路径,不管它是否可以通过添加或乘以节点来生成一个特定的数字。
换句话说,我想显示所有的数字,这些数字可以通过在路径节点之间添加*或+来生成。
注意,路径应该从根开始到叶。
例如:
树节点:10、8、3
此路径可以生成数字:
240=>10*8*3
110=>10*(8+3)
21=>10+8+3
83=>(10*8)+3
54=>(10+8)*3
34=>10+(8*3)
我写了这段代码,不包括括号。
私有void findThePath(TreeNode tnode,int result,int n,列表路径){
//如果node为空,则返回
if(tnode==null)
回报;
//adding nodes to this list, in order to save the path paths.add(tnode); // if node is leaf node, and its data equals // to user input, its path highlighted if (tnode.leftCircle == null && tnode.rightCircle == null) { if (result == n) { paths.forEach(t -> t.highlightFlag = true); paths.forEach(t -> System.out.print(t.rootCircle.getSearchKey() + " ")); } } // if left child exists, check for leaf, // and insert * or + sign between nodes, // recursively if (tnode.leftCircle != null) { findThePath(tnode.leftCircle, result + tnode.leftCircle.rootCircle.getSearchKey(), n, paths); findThePath(tnode.leftCircle, result * tnode.leftCircle.rootCircle.getSearchKey(), n, paths); } // if right child exists, check for leaf // and insert * or + sign between nodes, // recursively if (tnode.rightCircle != null) { findThePath(tnode.rightCircle, result + tnode.rightCircle.rootCircle.getSearchKey(), n, paths); findThePath(tnode.rightCircle, result * tnode.rightCircle.rootCircle.getSearchKey(), n, paths); } //we need to remove the last node in list because //its not in left or right of the nodes paths.remove(paths.size() - 1);}
see the output here:
它不包含8*(5+3)和8+(5*3)。

最佳答案

如果生成的节点数是针对三个节点的,则递归遍历树,并在每个节点检查它是否同时具有左节点和右节点,以便运行给定的方程,如果它提供了编号,则打印节点。

关于algorithm - 通过加或乘节点查找树可以生成的所有数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53969534/

10-10 15:10