File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change 1+ /* ***********************************************************
2+
3+ Following is the structure for the TreeNode class
4+
5+ template <typename T>
6+ class TreeNode {
7+ public:
8+ T data;
9+ vector<TreeNode<T>*> children;
10+
11+ TreeNode(T data) {
12+ this->data = data;
13+ }
14+
15+ ~TreeNode() {
16+ for (int i = 0; i < children.size(); i++) {
17+ delete children[i];
18+ }
19+ }
20+ };
21+
22+ ************************************************************/
23+ class helper {
24+ public :
25+ TreeNode<int >* m;
26+ TreeNode<int >* sm;
27+
28+ helper (TreeNode<int >* m, TreeNode<int >* sm) {
29+ this ->m = m;
30+ this ->sm = sm;
31+ }
32+ };
33+
34+ helper help (TreeNode<int >* root) {
35+ if (root==NULL ){
36+ helper r (NULL ,NULL );
37+ return r;
38+ }
39+ helper ans (root, NULL );
40+ for (int i = 0 ; i < root->children .size (); i++) {
41+ helper child = help (root -> children[i]);
42+ if (child.m ->data > ans.m ->data ){
43+ if (child.sm ==NULL ){
44+ ans.sm =ans.m ;
45+ ans.m =child.m ;
46+ }
47+ else {
48+ if (child.sm ->data > ans.m ->data ){
49+ ans.sm =child.sm ;
50+ ans.m =child.m ;
51+ }
52+ else {
53+ ans.sm =ans.m ;
54+ ans.m =child.m ;
55+ }
56+ }
57+ }
58+ else {
59+ if (ans.m ->data !=child.m ->data && (ans.sm ==NULL || child.m ->data > ans.sm ->data )){
60+ ans.sm =child.m ;
61+ }
62+ }
63+ }
64+ return ans;
65+ }
66+
67+ TreeNode<int >* getSecondLargestNode (TreeNode<int >* root) {
68+ // Write your code here
69+ if (root == NULL ) return NULL ;
70+ helper ans = help (root);
71+ return ans.sm ;
72+ }
You can’t perform that action at this time.
0 commit comments