Prove safety offer0510: 1, a symmetrical binary tree; 2 binary tree zigzag print order; 3 binary tree into multiple lines printed

1, a symmetrical binary tree

Title Description
Please implement a function, a binary tree is used to determine not symmetrical. Note that if a binary image is a binary tree with this same definition as symmetrical.

Note: just saw the title, think the idea is to find a mirror image of this binary tree binary tree, and then judge, now found ideas are wrong, the key topic is "If a binary tree with this binary tree is a mirror image of the same"
look Comments Notes District: Mark
/ * ideas: first, the root and the left and right sub-tree, the same tree in the left and right sub-sub-sub-tree of the tree in the left and right subtree

  • Left subtree right subtree and the right subtree of the same to the left sub-tree, the recursive
  • It may be non-recursive, using sub-stack or queue access levels root node
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        def is_same(p1,p2):
            if not p1 and not p2:
                return True
            if (p1 and p2) and p1.val == p2.val:
                return is_same(p1.left,p2.right) and is_same(p1.right,p2.left)
            return False
            
        if not pRoot:
            return True
        if not pRoot.left and pRoot.right:
            return False
        if not pRoot.right and pRoot.left:
            return False
        return is_same(pRoot.left,pRoot.right)
        

2, the order of printing the binary tree zigzag

Title Description
Please implement a function according to a binary tree zigzag print, i.e., the first row from left to right order of printing, the print order of the second layer is from right to left, the third row from left to right order of printing, other line and so on.

Notes: classic topics, the general method algorithm complexity is high time and space, read resolution, and overwhelmingly the answer, saw a total of three kinds of answers, as follows
(link: https://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
source: cattle-off network

We are many implementations of each layer of data into the ArrayList, the reverse operation is performed even layer,

  • When huge amounts of data, so that efficiency is too low.
  • (I have an interview, test algorithm is zigzag print binary tree, with the reverse,
  • Directly despised, the interviewer said the efficiency of mass data simply do not work. )
  • Following implementation: each layer need not be stored into the data ArrayList, the reverse operation is performed even layers, deposited by direct printing order
  • Idea: to achieve a doubly linked list of features is the use of the underlying LinkedList in Java.
  • 1)可用做队列,实现树的层次遍历
    
  • 2)可双向遍历,奇数层时从前向后遍历,偶数层时从后向前遍历)
    

Solution 1:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        from collections import deque
        res,tmp = [],[]
        last = pRoot
        q = deque([pRoot])
        left_to_right = True
        while q:
            t = q.popleft()
            tmp.append(t.val)
            if t.left:
                q.append(t.left)
            if t.right:
                q.append(t.right)
            if t == last:
                res.append(tmp if left_to_right else tmp[::-1])
                tmp = []
                left_to_right = not left_to_right
                if q: last = q[-1]
        return res

Solution 2:
very clever method of thinking is very clear, I feel this is more suitable for the novice to understand and grasp

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        res = []
        odd = []
        even = []
        odd.append(pRoot)
        while odd or even:
            row = []
            while odd:
                tmp = odd.pop()
                row.append(tmp.val)
                if tmp.left:
                    even.append(tmp.left)
                if tmp.right:
                    even.append(tmp.right)
            if row:
                res.append(row)
            row = []
            while even:
                tmp = even.pop()
                row.append(tmp.val)
                if tmp.right:
                    odd.append(tmp.right)
                if tmp.left:
                    odd.append(tmp.left)
            if row:
                res.append(row)
        return res

Solution 3:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Print(self, root):
        # write code here
        if not root:
            return []
        c=[root]
        f=[]
        count=1
        while len(c)>0:
            d=[]
            e=[]
            for i in c:
                if i!=None:
                    d.append(i.val)
                    if i.left:
                        e.append(i.left)
                    if i.right:
                        e.append(i.right)
            if count%2==0:
                   d.reverse()
            f.append(d)
            c=e
            count=count+1
        return f

3, the binary tree print into multiple lines.

Title Description
top to bottom, binary print layer, the same layer as the output node from left to right. Each line of output layer.

Note: The last title to simplify the solution, any one of
their reform

#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        res = []
        p = []
        p.append(pRoot)
        while len(p)>0:
            c = []
            d = []
            while p:
                tmp = p.pop(0)
                d.append(tmp.val)
                if tmp.left:
                    c.append(tmp.left)
                if tmp.right:
                    c.append(tmp.right)
            res.append(d)
            p = c
        return res

Guess you like

Origin blog.csdn.net/Leia21/article/details/90083826