-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path988.smallest-string-starting-from-leaf.cpp
118 lines (117 loc) · 2.42 KB
/
988.smallest-string-starting-from-leaf.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
* @lc app=leetcode id=988 lang=cpp
*
* [988] Smallest String Starting From Leaf
*
* https://leetcode.com/problems/smallest-string-starting-from-leaf/description/
*
* algorithms
* Medium (51.94%)
* Total Accepted: 8.7K
* Total Submissions: 18K
* Testcase Example: '[0,1,2,3,4,3,4]'
*
* Given the root of a binary tree, each node has a value from 0 to 25
* representing the letters 'a' to 'z': a value of 0 represents 'a', a value of
* 1 represents 'b', and so on.
*
* Find the lexicographically smallest string that starts at a leaf of this
* tree and ends at the root.
*
* (As a reminder, any shorter prefix of a string is lexicographically smaller:
* for example, "ab" is lexicographically smaller than "aba". A leaf of a node
* is a node that has no children.)
*
*
*
*
*
*
*
*
*
*
*
* Example 1:
*
*
*
*
* Input: [0,1,2,3,4,3,4]
* Output: "dba"
*
*
*
* Example 2:
*
*
*
*
* Input: [25,1,3,1,3,0,2]
* Output: "adz"
*
*
*
* Example 3:
*
*
*
*
* Input: [2,2,1,null,1,0,null,0]
* Output: "abc"
*
*
*
*
* Note:
*
*
* The number of nodes in the given tree will be between 1 and 8500.
* Each node in the tree will have a value between 0 and 25.
*
*
*
*
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
string smallest;
string local;
void traverse(TreeNode* root, TreeNode* prev){
if(root == NULL){
// cout<<local<<" ";
if(prev!=NULL && (prev->left == NULL ^ prev->right == NULL)) return;
if(smallest == "")
smallest = local;
else if(smallest > local)
smallest = local;
return ;
}
string tmp = local;
local = (char)(root->val+'a') + local;
traverse(root->left, root);
traverse(root->right, root);
local = tmp;
}
string smallestFromLeaf(TreeNode* root) {
smallest = "";
local = "";
traverse(root, NULL);
// if(root->left == NULL)
// return traverse(root->right) + (char)(root->val+'a');
// else if(root->right == NULL)
// return traverse(root->left) + (char)(root->val+'a');
return smallest;
}
};