您的位置:首页 > 其它

【笔试】42、二叉树中和为某一值的路径

2015-09-05 11:08 477 查看
/****************************************************************************************
 *题目:二叉树中和为某一值的路径
 *      输入一颗二叉树和一个整数,打印出二叉树中节点值和尾输入整数的所有路径。从树的根节点开始往下一直到
 *      叶节点所经过的结点形成一条路径。
 *时间:2015年9月5日10:53:32
 *文件:PathInTree.java
 *作者:cutter_point
 ****************************************************************************************/
package bishi.Offer50.y2015.m09.d05;

import java.util.*;

import bishi.Offer50.y2015.m08.d26.*;

public class PathInTree
{

    public void findPath(BinaryTreeNode pRoot, int expectedSum)
    {
        if(pRoot == null)
            return;
        Vector<BinaryTreeNode> path = new Vector<BinaryTreeNode>();
        int currentSum = 0;
        findPath(pRoot, expectedSum, path, currentSum);
    }

    /**
     * 用来寻找我们的路径,我们用递归,这样就可以自动返回到前一个根节点了
     * @param pRoot 当前遍历到的节点
     * @param expectedSum       我们统计的目标
     * @param path  记录我们的路径
     * @param currentSum    当前的和
     */
    private void findPath(BinaryTreeNode pRoot, int expectedSum, Vector<BinaryTreeNode> path, int currentSum)
    {
        //把当前的节点的值添加进去
        currentSum += pRoot.m_nValue;
        path.add(pRoot);
        //是否就是我们的值,并且得是我们的叶节点
        boolean isLeaf = pRoot.m_pLeft == null && pRoot.m_pRight == null;
        if(isLeaf && currentSum == expectedSum)
        {
            System.out.println("路径已经找到:");
            for(int i = 0; i < path.size(); ++i)
            {
                System.out.print(path.get(i).m_nValue + "\t");
            }//for
            System.out.println();
        }//if

        //然后判断左右是否为空,如果还没有达到我们判定成功的值,那么继续递归下去
        if(pRoot.m_pLeft != null)
        {
            findPath(pRoot.m_pLeft, expectedSum, path, currentSum);
        }//if
        if(pRoot.m_pRight != null)
        {
            findPath(pRoot.m_pRight, expectedSum, path, currentSum);
        }//if

        //这样如果当前节点递归结束,没有达到成功,返回上一个节点的时候,我们把路径也返回
        currentSum -= pRoot.m_nValue;
        path.remove(pRoot);
    }

    public static void main(String[] args)
    {
        //                      1
        //              /               \
        //             2                 3
        //         /                /         \
        //        4                5           6
        //          \                        /
        //           7                      8
        //
        //我们的二叉树,用这个题的方法遍历的结果是
        //1  2  3  4  5  6  7  8
        //
        int preorder[] = {1,2,4,7,3,5,6,8};
        int inorder[] = {4,7,2,1,5,3,8,6};
        BinaryTree bt = new BinaryTree();
        bt.construct(preorder, inorder);
        PathInTree pit = new PathInTree();
        pit.findPath(bt.root, 9);
    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: