Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
TREE - path from root to leaf with given sum
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//All tree traversal #include <iostream> #include <queue> #include <string> #include <list> using namespace std; struct node { int data; node* left; node* right; node(int d): data(d), left(NULL), right(NULL) {} node(int d, node* l, node* r): data(d), left(l), right(r) {} }; void pathToGivenSum(node* root, int findSum, list<node*>& properLeaves, int curSum = 0) { if (!root) return; int sum = curSum + root->data; if (findSum == sum && !root->left && !root->right) { cout << root->data << " "; properLeaves.push_back(root); } pathToGivenSum(root->left, findSum, properLeaves, sum); pathToGivenSum(root->right, findSum, properLeaves, sum); } // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 // / \ // 8 9 int main() { node *h = new node(9, NULL, NULL); node *j = new node(8, NULL, NULL); node *g = new node(7, NULL, NULL); node *f = new node(6, j, h); node *e = new node(5, NULL, NULL); node *d = new node(4, NULL, NULL); node *c = new node(3, f, g); node *b = new node(2, d, e); node *a = new node(1, b, c); list<node*> leaves; pathToGivenSum(a, 11, leaves); }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.36 sec, absolute running time: 0.14 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 0.52 sec
fork mode
|
history
|
discussion
7