Skip to content

Commit 4a05883

Browse files
committed
add binary-tree-right-side-view problem
1 parent 2f7d952 commit 4a05883

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ This is my way of saying - change your interview style. There are lots of smart
1818
| [Coin change](https://leetcode.com/problems/coin-change/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/coin-change.rb) |
1919
| [Decode Strings](https://leetcode.com/problems/decode-string/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/decode_string.rb) |
2020
| [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/wiggle_subsequence.rb) |
21+
| [Binary Tree Side View](https://leetcode.com/problems/binary-tree-right-side-view/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/binary_tree_side_view.rb) |
2122
| [Unix path](https://leetcode.com/problems/simplify-path/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/simplify_path.rb) |
2223
| [Array Product](https://leetcode.com/problems/product-of-array-except-self/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/product-of-array.rb) |
2324
| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/top-k-elements.rb) |

src/binary_tree_side_view.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode
3+
# attr_accessor :val, :left, :right
4+
# def initialize(val)
5+
# @val = val
6+
# @left, @right = nil, nil
7+
# end
8+
# end
9+
10+
# @param {TreeNode} root
11+
# @return {Integer[]}
12+
def right_side_view(root)
13+
q = [[root]]
14+
res = []
15+
while q.any?
16+
nodes = q.shift
17+
new_list = []
18+
last = nil
19+
nodes.each do |n|
20+
if n
21+
new_list += [n.left,n.right]
22+
last = n
23+
end
24+
end
25+
q << new_list if new_list.any?
26+
res << last.val if last
27+
end
28+
return res
29+
end
30+
31+
# p right_side_view([1,2,3,null,5,null,4]) # => [1,3,4]

0 commit comments

Comments
 (0)