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

/****************************************************************************************
 *题目:二叉树中和为某一值的路径
 *      输入一颗二叉树和一个整数,打印出二叉树中节点值和尾输入整数的所有路径。从树的根节点开始往下一直到
 *      叶节点所经过的结点形成一条路径。
 *时间: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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值