ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

获取从根到叶路径形成的所有节点的总和

前开发者教程 2020年10月8日

题: 

给定一个二叉树根节点,获取从根到叶节点形成的所有节点的值之和。

解:

从上面的图像中,我们有4个叶节点,即:3、4、6、7
所以路径将是
1-> 2 -> 3 Number = 123
1-> 2 -> 4 Number = 124
1-> 5 -> 6 Number = 156
1-> 5 -> 7 Number = 157
因此总和为:
123 + 124 + 156 + 157 = 560
解决方案是进行预遍历并跟踪计算到该节点的值。
对于每个节点,将值乘以10 +节点’s data.

C ++解决方案

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};


int value_root_to_leaf;

void sum_root_to_leaf(Node *node, int i) 
{
    if (node == NULL) 
    {
      return;
    }

    if (node->left == NULL && node->right == NULL) 
    {
      value_root_to_leaf = value_root_to_leaf + (i * 10 + node->data);
      return;
    }

    sum_root_to_leaf(node->left, i * 10 + node->data);
    sum_root_to_leaf(node->right, i * 10 + node->data);
}



int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              1
            /   \
           /     \
          2       5
         /  \    /  \
        /    \  /    \
       3     4 6      7

    */

    root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(5);
    root->left->left = new Node(3);
    root->left->right = new Node(4);
    root->right->left = new Node(6);
    root->right->right = new Node(7);

    sum_root_to_leaf(root, 0);

    cout<<"The sum of root to leaf is "<<value_root_to_leaf<<endl;

    return 0;  
}

输出量

The sum of root to leaf is 560
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的

<pre id="VtHEXd7" class="VoD7BIy"><frameset class="yFgICyL"><base id="IaXoxnS" class="IxLOnYx"><address id="F1GOKLb" class="FfqKZey"></address></base></frameset></pre>

        <i id="Ey6e9kJ"></i>


          <ins class="zzoZEzF"><optgroup id="QoHmUjo" class="Q7R40fn"><details id="D2z1J3i"></details></optgroup></ins>
        1. <details id="a2uDtZd" class="azc5hUn"><dt id="OTKc28y" class="O2gIpCV"><details id="xcW1bWM"></details></dt></details>


              <tbody id="FJ1XZxQ" class="F8WAbDm"><option class="Kl6FF1c"><option class="yyxxunV"><datalist id="j4r5xyj" class="jS8d97N"></datalist></option></option></tbody>