To the Top
File:  root - text - article - 2019 - 10 - invert-a-binary-tree.txt
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | English | Home Page | Category: Computing | 329 Views, 14891 Search Bots | 164 Words

Subscribe to Feed Burner | Browse | Archive
Hi, here's your problem today. This problem was recently asked by Twitter:

You are given the root of a binary tree. Invert the binary tree in place. That is, all left children should become right children, and all right children should become left children.

Example:


a
/ \
b c
/ \ /
d e f


The inverted version of this tree is as follows:


a
/ \
c b
\ / \
f e d


Here is the function signature:


class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def preorder(self):
print self.value,
if self.left: self.left.preorder()
if self.right: self.right.preorder()

def invert(node):
# Fill this in.

root = Node('a')
root.left = Node('b')
root.right = Node('c')
root.left.left = Node('d')
root.left.right = Node('e')
root.right.left = Node('f')

root.preorder()
# a b d e c f
print "\n"
invert(root)
root.preorder()
# a c f b e d
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Problem, Data Structures and Algorithms, | English | Home Page | Cateogry: Computing | 329 Views, 14891 Search Bots | 164 Words Subscribe to Feed Burner

Related Articles

  1. Daily Interview Problem: Count Number of Unival Subtrees
  2. Algorithm Interview Question: Symmetric k-ary Tree
  3. Two Tricks of Delphi
  4. [Daily Problem] Longest Increasing Subsequence
  5. Daily Interview Problem: Word Ordering in a Different Alphabetical Order
  6. ImageMagick Vulnerabilities -  CVE-2016–3714
  7. Daily Interview Problem: Longest Substring With K Distinct Characters
  8. Compare Version Numbers
  9. Daily Interview Problem: Buddy Strings
  10. Palindrome Integers

Comments (0)

Your Email (Domain Part Not Exposed):

Your Comments:

Privately By Mail Colors More Smileys S x y @

Verification (Click Image 2 Refresh):

    Be the first one to comment this page !


Page Edited: October 30 2020 14:21:09 | RSS Subscription
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />