File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * function TreeNode(val, left, right) {
4+ * this.val = (val===undefined ? 0 : val)
5+ * this.left = (left===undefined ? null : left)
6+ * this.right = (right===undefined ? null : right)
7+ * }
8+ */
9+ /**
10+ * Tree | Backtracking
11+ * Time O(n^2) | Space O(n)
12+ * https://leetcode.com/problems/smallest-string-starting-from-leaf/
13+ * @param {TreeNode } root
14+ * @return {string }
15+ */
16+ var smallestFromLeaf = function ( root ) {
17+
18+ let biggestStr = new Array ( 8500 ) . fill ( "z" ) ;
19+ biggestStr = biggestStr . join ( "" ) ;
20+
21+ let smallest = biggestStr ;
22+ const dfs = ( node , str ) => {
23+
24+ const char = String . fromCharCode ( node . val + 97 ) ;
25+
26+ if ( ! node . left && ! node . right ) {
27+ str . push ( char ) ;
28+ const str1 = str . slice ( 0 ) . reverse ( ) . join ( "" ) ;
29+ if ( str1 < smallest ) {
30+ smallest = str1 ;
31+ }
32+ str . pop ( ) ;
33+ return ;
34+
35+ }
36+
37+ if ( node . left ) {
38+ str . push ( char ) ;
39+ dfs ( node . left , str ) ;
40+ str . pop ( ) ;
41+ }
42+
43+ if ( node . right ) {
44+ str . push ( char ) ;
45+ dfs ( node . right , str ) ;
46+ str . pop ( ) ;
47+ }
48+ }
49+
50+ dfs ( root , [ ] ) ;
51+
52+ return smallest ;
53+ } ;
You can’t perform that action at this time.
0 commit comments