题:
给定一个二叉树根节点,获取从根到叶节点形成的所有节点的值之和。
解:
从上面的图像中,我们有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