题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径.
核心代码:
<pre><code>`
var path:[String] = []
var listPath:[[String]] = []
func findTreePath(rootNode:TreeNode?,targert:Int)->[[String]]? {
if rootNode == nil {
return nil
}
path.append((rootNode?.data)!)
let value:Int = Int((rootNode?.data)!)!
var temp = targert
temp -= value
if temp == 0 && rootNode?.leftChild == nil && rootNode?.rightChild == nil {
listPath.append(path) // 路径添加
}
//
if rootNode?.leftChild != nil {// 递归遍历左子树
_ = findTreePath(rootNode: rootNode?.leftChild, targert: temp)
}
if rootNode?.rightChild != nil { // 递归遍历右子树
_ = findTreePath(rootNode: rootNode?.rightChild, targert: temp)
}
path.remove(at: path.count-1) // 回溯到父节点
return listPath
}`</code></pre>
测试代码:
<pre><code>`
var util:TreeUtil = TreeUtil()
var rootData:[String] = ["10","5","4","#","#","7","#","#","12","#","#"]
var preRootNode:TreeNode?
util.createTreeByPreOrderData(root: &preRootNode, listData: rootData)
var treePath:BinaryTreePath = BinaryTreePath()
var target = 22
var result = treePath.findTreePath(rootNode: preRootNode, targert: target)
print("FlyElephant-和(target)的路径---(result!)")`</code></pre>