【IT笔试面试题整理】二叉树中和为某一值的路径--从根到叶子节点

来源:互联网 发布:好看的美国电影 知乎 编辑:程序博客网 时间:2024/05/01 17:01

 

【试题描述】

 

输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条
路径。打印出和与输入整数相等的所有路径。
例如输入整数 22 和如下二元树
                    10
                   /    \
                 5      12

               /    \ 
             4      7
则打印出两条路径:10, 12 和 10, 5, 7。

据说这是百度的一道笔试题。

 

分析:这道题考查对二叉树遍历方式的理解,采用后序遍历,如果把二叉树看成图,就是图的深度遍历。使用变量存放当前遍历的路径和,当访问到某一结点时,把该结点添加到路径上,并累加当前结点的值。如果当前结点为叶结点并且当前路径的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到父结点,因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是根结点到父结点的路径。

 

【参考代码】

 1     public static void findPath(Node root, int sum, int curSum, LinkedList path) 2     { 3         if (root == null) 4             return; 5         curSum += root.value; 6         path.add(root.value); 7  8         // if the node is a leaf, and the sum is same as pre-defined, 9         // the path is what we want. print the path10         if (root.left == null && root.right == null && curSum == sum)11         {12             System.out.println("Find a path: ");13             Iterator it = path.iterator();14             while (it.hasNext())15             {16                 System.out.print(it.next() + " ");// 打印路径节点的值17             }18             System.out.println();19         }20 21         // if the node is not a leaf, goto its children22         if (root.left != null)23             findPath(root.left, sum, curSum, path);24         if (root.right != null)25             findPath(root.right, sum, curSum, path);26 27         // when we finish visiting a node and return to its parent node,28         // we should delete this node from the path and29         // minus the node's value from the current sum30         curSum -= root.value;31         path.pollLast();32     }

 

 

 

阅读全文
0 0
原创粉丝点击