Merge pull request #13 from spencerking/binary_tree

Adding binary tree traversal and inversion
This commit is contained in:
Chetan Kaushik 2017-11-05 22:57:30 +05:30 committed by GitHub
commit 44f05ed565
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 89 additions and 0 deletions

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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