File tree Expand file tree Collapse file tree 1 file changed +88
-0
lines changed
Smallest String Starting From Leaf Expand file tree Collapse file tree 1 file changed +88
-0
lines changed Original file line number Diff line number Diff line change 1+ // Runtime: 24 ms, faster than 7.50% of C++ online submissions for Smallest String Starting From Leaf.
2+ // Memory Usage: 19.6 MB, less than 91.30% of C++ online submissions for Smallest String Starting From Leaf.
3+
4+ /* *
5+ * Definition for a binary tree node.
6+ * struct TreeNode {
7+ * int val;
8+ * TreeNode *left;
9+ * TreeNode *right;
10+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+ * };
12+ */
13+ class Solution
14+ {
15+ public:
16+ string smallestFromLeaf (TreeNode* root)
17+ {
18+ string curString = " " , minString = " " ;
19+
20+ TreeNode* preNode = nullptr ;
21+ stack<TreeNode*> memo;
22+
23+ while (root || !memo.empty ())
24+ {
25+ while (root)
26+ {
27+ curString += root->val + ' a' ;
28+
29+ memo.push (root);
30+ root = root->left ;
31+ }
32+ if (!memo.empty ())
33+ {
34+ root = memo.top ();
35+ memo.pop ();
36+
37+ if (root->right == nullptr || root->right == preNode)
38+ {
39+ if (root->left == nullptr && root->right == nullptr )
40+ {
41+ if (minString.length () == 0 || smaller (curString, minString))
42+ {
43+ minString = curString;
44+ }
45+ }
46+
47+ curString.pop_back ();
48+
49+ preNode = root;
50+ root = nullptr ;
51+ }
52+ else
53+ {
54+ memo.push (root);
55+ root = root->right ;
56+ }
57+ }
58+ }
59+
60+ reverse (minString.begin (), minString.end ());
61+ return minString;
62+ }
63+ private:
64+ bool smaller (const string& str1, const string& str2)
65+ {
66+ int ptr1 = str1.length () - 1 ;
67+ int ptr2 = str2.length () - 1 ;
68+
69+ while (ptr1 >= 0 && ptr2 >= 0 )
70+ {
71+ if (str1[ptr1] < str2[ptr2])
72+ {
73+ return true ;
74+ }
75+ else if (str1[ptr1] > str2[ptr2])
76+ {
77+ return false ;
78+ }
79+ else
80+ {
81+ --ptr1;
82+ --ptr2;
83+ }
84+ }
85+
86+ return ptr1 >= 0 ? false : true ;
87+ }
88+ };
You can’t perform that action at this time.
0 commit comments