diff --git a/data_structures/binary_trees/inorder_traversal.rb b/data_structures/binary_trees/inorder_traversal.rb new file mode 100644 index 0000000..45605fc --- /dev/null +++ b/data_structures/binary_trees/inorder_traversal.rb @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val) +# @val = val +# @left, @right = nil, nil +# end +# end + +# @param {TreeNode} root +# @return {Integer[]} +def inorder_traversal(root) + ans = [] + def traverse(node, ans) + if node != nil + traverse(node.left, ans) + ans.push(node.val) + traverse(node.right,ans) + end + end + traverse(root,ans) + return ans +end \ No newline at end of file diff --git a/data_structures/binary_trees/invert.rb b/data_structures/binary_trees/invert.rb new file mode 100644 index 0000000..8411e19 --- /dev/null +++ b/data_structures/binary_trees/invert.rb @@ -0,0 +1,20 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val) +# @val = val +# @left, @right = nil, nil +# end +# end + +# @param {TreeNode} root +# @return {TreeNode} +def invert_tree(root) + if root == nil + return nil + end + temp = root.left + root.left = invert_tree(root.right) + root.right = invert_tree(temp) + return root +end \ No newline at end of file diff --git a/data_structures/binary_trees/postorder_traversal.rb b/data_structures/binary_trees/postorder_traversal.rb new file mode 100644 index 0000000..d573642 --- /dev/null +++ b/data_structures/binary_trees/postorder_traversal.rb @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val) +# @val = val +# @left, @right = nil, nil +# end +# end + +# @param {TreeNode} root +# @return {Integer[]} +def postorder_traversal(root) + ans = [] + def traverse(node, ans) + if node != nil + traverse(node.left, ans) + traverse(node.right,ans) + ans.push(node.val) + end + end + traverse(root,ans) + return ans +end \ No newline at end of file diff --git a/data_structures/binary_trees/preorder_traversal.rb b/data_structures/binary_trees/preorder_traversal.rb new file mode 100644 index 0000000..c366b5c --- /dev/null +++ b/data_structures/binary_trees/preorder_traversal.rb @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val) +# @val = val +# @left, @right = nil, nil +# end +# end + +# @param {TreeNode} root +# @return {Integer[]} +def preorder_traversal(root) + ans = [] + def traverse(node, ans) + if node != nil + ans.push(node.val) + traverse(node.left, ans) + traverse(node.right,ans) + end + end + traverse(root,ans) + return ans +end \ No newline at end of file