Ch4.8: find all the path that a Binary tree sums up to a given value, may/maynot have parent pointer

本文介绍了一种优化算法,用于从树的子节点向上求和至父节点,实现路径和的高效计算。通过平衡树构建和递归打印算法,展示了如何在二叉树中查找所有可能的路径和,并在特定值时进行路径搜索。代码示例清晰地展示了算法的实现过程,包括路径打印、最大高度计算、整数转字符串等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In this problem, we should consider the path to the bottom, instead of hit-and-run. As a result, the recursive starts summation from the children up to their parents not from up to down.

For example:

The given sums up value is 8:

then these are all correct paths:

8;

8=-2=2;

2=0=6;

2=0=6=-1=1;


Here is the full code. Very well design.

//http://leetcode.com/2010/09/how-to-pretty-print-binary-tree.html

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

struct BinaryTree {
  BinaryTree *parent, *left, *right;
  int data;
  BinaryTree(int val) : parent(NULL), left(NULL), right(NULL), data(val) { }
};

class BTree{
private:
    BinaryTree *m_root;
public:
    BTree(): m_root(NULL){}
    BTree(BinaryTree *t): m_root(t){}

    BinaryTree* getRoot() const{return m_root;}
    
    BinaryTree* balanceTree(BinaryTree* pnode, BinaryTree *parent, int *arr, int low, int high){
        if(low>high || arr == NULL)
            return NULL;
        int mid = (low+high)>>1;
        pnode = new BinaryTree(arr[mid]);
        pnode->parent = parent;
        pnode->left = balanceTree(pnode->left, pnode, arr, low, mid-1);
        pnode->right = balanceTree(pnode->right, pnode, arr, mid+1, high);

        return pnode;
    }

    void PrintPre(BinaryTree *pnode)
    {
        if(pnode == NULL)
            return;
 
        cout << pnode->data << " ";
        PrintPre(pnode->left);
        PrintPre(pnode->right);        
    }


// Find the maximum height of the binary tree
int maxHeight(BinaryTree *p) {
  if (!p) return 0;
  int leftHeight = maxHeight(p->left);
  int rightHeight = maxHeight(p->right);
  return (leftHeight > rightHeight) ? leftHeight + 1: rightHeight + 1;
}

// Convert an integer value to string
string intToString(int val) {
  ostringstream ss;
  ss << val;
  return ss.str();
}

// Print the arm branches (eg, /    \ ) on a line
void printBranches(int branchLen, int nodeSpaceLen, int startLen, int nodesInThisLevel, const deque& nodesQueue, ostream& out) {
  deque::const_iterator iter = nodesQueue.begin();
  for (int i = 0; i < nodesInThisLevel / 2; i++) {
    out << ((i == 0) ? setw(startLen-1) : setw(nodeSpaceLen-2)) << "" << ((*iter++) ? "/" : " ");
    out << setw(2*branchLen+2) << "" << ((*iter++) ? "\\" : " ");
  }
  out << endl;
}

// Print the branches and node (eg, ___10___ )
void printNodes(int branchLen, int nodeSpaceLen, int startLen, int nodesInThisLevel, const deque& nodesQueue, ostream& out) {
  deque::const_iterator iter = nodesQueue.begin();
  for (int i = 0; i < nodesInThisLevel; i++, iter++) {
    out << ((i == 0) ? setw(startLen) : setw(nodeSpaceLen)) << "" << ((*iter && (*iter)->left) ? setfill('_') : setfill(' '));
    out << setw(branchLen+2) << ((*iter) ? intToString((*iter)->data) : "");
    out << ((*iter && (*iter)->right) ? setfill('_') : setfill(' ')) << setw(branchLen) << "" << setfill(' ');
  }
  out << endl;
}

// Print the leaves only (just for the bottom row)
void printLeaves(int indentSpace, int level, int nodesInThisLevel, const deque& nodesQueue, ostream& out) {
  deque::const_iterator iter = nodesQueue.begin();
  for (int i = 0; i < nodesInThisLevel; i++, iter++) {
    out << ((i == 0) ? setw(indentSpace+2) : setw(2*level+2)) << ((*iter) ? intToString((*iter)->data) : "");
  }
  out << endl;
}

// Pretty formatting of a binary tree to the output stream
// @ param
// level  Control how wide you want the tree to sparse (eg, level 1 has the minimum space between nodes, while level 2 has a larger space between nodes)
// indentSpace  Change this to add some indent space to the left (eg, indentSpace of 0 means the lowest level of the left node will stick to the left margin)
void printPretty(BinaryTree *root, int level, int indentSpace, ostream& out) {
  int h = maxHeight(root);
  int nodesInThisLevel = 1;

  int branchLen = 2*((int)pow(2.0,h)-1) - (3-level)*(int)pow(2.0,h-1);  // eq of the length of branch for each node of each level
  int nodeSpaceLen = 2 + (level+1)*(int)pow(2.0,h);  // distance between left neighbor node's right arm and right neighbor node's left arm
  int startLen = branchLen + (3-level) + indentSpace;  // starting space to the first node to print of each level (for the left most node of each level only)

  deque nodesQueue;
  nodesQueue.push_back(root);
  for (int r = 1; r < h; r++) {
    printBranches(branchLen, nodeSpaceLen, startLen, nodesInThisLevel, nodesQueue, out);
    branchLen = branchLen/2 - 1;
    nodeSpaceLen = nodeSpaceLen/2 + 1;
    startLen = branchLen + (3-level) + indentSpace;
    printNodes(branchLen, nodeSpaceLen, startLen, nodesInThisLevel, nodesQueue, out);

    for (int i = 0; i < nodesInThisLevel; i++) {
      BinaryTree *currNode = nodesQueue.front();
      nodesQueue.pop_front();
      if (currNode) {
          nodesQueue.push_back(currNode->left);
          nodesQueue.push_back(currNode->right);
      } else {
        nodesQueue.push_back(NULL);
        nodesQueue.push_back(NULL);
      }
    }
    nodesInThisLevel *= 2;
  }
  printBranches(branchLen, nodeSpaceLen, startLen, nodesInThisLevel, nodesQueue, out);
  printLeaves(indentSpace, level, nodesInThisLevel, nodesQueue, out);
}


void printREV(BinaryTree* head, int level){
    vector v;
    for(int i=0; idata);
        head = head->parent;
    }
    while(!v.empty()){
        cout<balanceTree(bt2->getRoot(), NULL, a2, low2, high2);
    bt2 = new BTree(proot2);
    bt2->PrintPre(bt2->getRoot());
    cout << "Tree pretty print with level=1 and indentSpace=0\n\n";
  // Output to console
  bt2->printPretty(proot2, 1, 0, cout);
  
  
  // 
  int sum = 8;
  cout << "\nall the paths sums to: "<< sum<find_sum(proot2, sum);
  
  
  cout << "if Struct BinaryTree doesn't have parent pointer.........\n";
  vector v_additional;
  bt2->find_sum2(proot2, sum, v_additional, 0);
  return 0;
}

/*
Executing the program....
$demo 
a2:
0----------13
5 8 4 3 -2 0 2 2 -3 3 4 0 1 6 Tree pretty print with level=1 and indentSpace=0


        _______5______
       /              \
    ___8__          ___2__
   /      \        /      \
   4      -2      -3      _0
    \    /  \    /  \    /  \
     3   0   2   3   4   1   6

all the paths sums to: 8
if Struct BinaryTree has parent pointer.........
8 
8 -2 2 
5 2 -3 4 
5 2 0 1 
2 0 6 
if Struct BinaryTree doesn't have parent pointer.........
8 
8 -2 2 
5 2 -3 4 
5 2 0 1 
2 0 6 
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值