题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径.
核心代码:
<pre><code>` var pathList:[[String]] = []
var path:[String] = []
func findPath(root:TreeNode?,targetNum:Int) {
if root == nil {
return
}
path.append(root!.data!)
let target:Int = targetNum - Int(root!.data!)!
// 叶子节点,且满足要求
if target == 0 && root?.leftChild == nil && root?.rightChild == nil {
pathList.append(path)
}
// 遍历左子节点
if root?.leftChild != nil {
findPath(root: root?.leftChild, targetNum: target)
}
// 遍历右子节点
if root?.rightChild != nil {
findPath(root: root?.rightChild, targetNum: target)
}
path.removeLast()
}`</code></pre>
测试数据:
<pre><code>`var sumListData:[String] = ["10","5","4","#","#","7","#","#","12","#","#"]
var sumNode:TreeNode?
tree.rootIndex = -1
tree.createTreeByPreOrder(root: &sumNode, listData: sumListData)
binaryTree.findPath(root: sumNode, targetNum: 22)
print("FlyElephant---和的路径----(binaryTree.pathList)")`</code></pre>
网友评论