美文网首页
(*)剑指offer 面试题25:二叉树中和为某一值的路径

(*)剑指offer 面试题25:二叉树中和为某一值的路径

作者: qmss | 来源:发表于2016-06-25 20:21 被阅读0次

    题目:
    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从根结点开始往下一直到叶结点所经过的结点形成一条路径。

    struct BinaryTreeNode {
        int                                          m_nValue;
        BinaryTreeNode*                    m_pLeft;
        BinaryTreeNode*                    m_pRight;
    };
    

    解法:

    void findPath(BinaryTreeNode*  pRoot, int expectSum) {
        if (pRoot == 0)  return;
        std::vector<int>  path;
        int  currentSum = 0;  
        findPathRecursive(pRoot, expectSum, path, currentSum);
    }
    
    void findPathRecursive(BinaryTreeNode*  pRoot, int expectSum, std::vector<int>  path,  int currentSum) {
        if (pRoot == 0)  return;
        path.push_back(pRoot->m_nValue);
        currentSum += pRoot->m_nValue;
        
        bool isLeaf  =  pRoot->m_pLeft == 0 && pRoot->m_pRight == 0;
        if (expectSum == currentSum && isLeaf) {
            // find path
            print(path);
        }
    
        if (pRoot->m_pLeft != 0) {
            findPathRecursive(pRoot->m_pLeft, expectSum, path, currentSum);
        }
        if (pRoot->m_pRight != 0) {
            findPathRecursive(pRoot->m_pRight, expectSum, path, currentSum);
        }
        
        //返回父节点之前,在路径上删除当前结点
        currentSum -= pRoot->m_nValue;
        path.pop_back();
    }
    

    相关文章

      网友评论

          本文标题:(*)剑指offer 面试题25:二叉树中和为某一值的路径

          本文链接:https://www.haomeiwen.com/subject/pjeadttx.html