Skip to content

Tree #54

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tech-cow opened this issue Mar 14, 2019 · 7 comments
Closed

Tree #54

tech-cow opened this issue Mar 14, 2019 · 7 comments

Comments

@tech-cow
Copy link
Owner

tech-cow commented Mar 14, 2019

妈蛋。FLAG全挂,今年9月再来一次,好好刷题。

@tech-cow
Copy link
Owner Author

tech-cow commented Mar 14, 2019

跟高度密切结合的题目

104. Maximum Depth of Binary Tree

Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

Base Case: 当Node为空的时候,返回高度为0

Recursive Rule精确版本 :
传递: 左右孩子
向下索取:下一层的左子树和右子树索取最高深度
向上返回:选择更高的深度并且加上当前层数的高度 (+1) 。最终返回。

Recursive Rule说人话:
谁高取谁,并加一

class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        left = self.maxDepth(root.left)
        right= self.maxDepth(root.right)
        return max(left, right) + 1




559. Maximum Depth of N-ary Tree

Base Case:
当Node为空的时候,返回高度为0
如果需要提前Dereference node.children,那么同时也要给node.children做一个basecase,返回高度1

Recursive Rule精确版本 :
传递: root.children
向下索取:下一层的所有孩子的最高深度
向上返回:选择更高的深度并且加上当前层数的高度 (+1) 。最终返回。

Recursive Rule说人话:
谁高取谁,并加一

换汤不换药做法

Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H * Tempoaray List Space)) Maximum nodes within the temporary call stack, along with a list initialized on each level of call stack.

# Readable
class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        if not root.children: return 1
        height = []
        for node in root.children:
            height.append(self.maxDepth(node))
        return max(height) + 1

#Pythonic
class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        if not root.children: return 1
        height = [self.maxDepth(node) for node in root.children]
        return max(height) + 1

利用变量代替每层的Temporary List

Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        height = 0
        for node in root.children:
            height = max(self.maxDepth(node), height)
        return height + 1

543. Diameter of Binary Tree

Base Case:
当Node为空的时候,返回高度为0

Recursive Rule :
传递: 左右子孩子
向下索取:下一层的左孩子和有孩子的最高深度
处理返回上来的参数:边长无非就是左边和右边传递上来的高度合,将其和全球变量比对并且取大保存
向上返回:选择更高的深度并且加上当前层数的高度 (+1) 。最终返回。

题解思路

这题的Recursive Rule基本等同于LC104,唯一区别是在向上反的过程中,计算了当前层的Node的边长:
cur_diameter = left + right

也就是左右孩子传递上来的高度之和,因为这道题的定义是求取最长的边长,所以当前层数的边长还需要和全球变量比对,然后更新全球变量的值

self.max_diameter = max(self.max_diameter, cur_diameter)

代码

Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

class Solution(object):
    def diameterOfBinaryTree(self, root):
        self.max_diameter = 0
        self.dfsHelper(root)
        return self.max_diameter

        
    def dfsHelper(self, root):
        if not root: return 0
        left = self.dfsHelper(root.left)
        right = self.dfsHelper(root.right)
        cur_diameter = left + right
        self.max_diameter = max(self.max_diameter, cur_diameter)
        return max(left, right) + 1

@tech-cow
Copy link
Owner Author

tech-cow commented Mar 14, 2019

两个Node之间的比较,跟换一类题

100. Same Tree

Time: O(N + M) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

Base Case: 当任意Node触底,比较该Node和另一个传递下来的Node的关系
如果都为空,返回True,如果不平衡返回False

Recursive Rule:
传递:左右孩子
索取:左右孩子
返回: 如果两个Node一样,返回True

class Solution(object):
    def isSameTree(self, p, q):
        # Base: 平衡的情况
        if not p and not q: return True
        if not p or not q: return False
        
        # 索取: 两个Node的左孩子和右孩子是否相等
        left = self.isSameTree(p.left, q.left)
        right = self.isSameTree(p.right, q.right)
        
        # 如果Value一样,返回True。
        return p.val == q.val and left and right



101. Symmetric Tree

Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

Base Case: 当任意Node触底,比较该Node和另一个传递下来的Node的关系
如果都为空,返回True,如果不平衡返回False

Recursive Rule:
传递: 两个Node
索取:两个Node的子孩子是否Symmetric
返回: 如果两个Node一样,返回True

class Solution(object):
    def isSymmetric(self, root):
        if not root: return True
        return self.isSymmetricHelper(root.left, root.right)
    
    def isSymmetricHelper(self, n1, n2):
        # Base Case:当两个Node任意触底,是否平衡
        if not n1 and not n2: return True
        if not n1 or not n2: return False
        
        # 传递: 2个Node
        # 索取: 子孩子是否Symmetric
        out_nodes = self.isSymmetricHelper(n1.left, n2.right)
        in_nodes = self.isSymmetricHelper(n1.right, n2.left) 
        
        # 返回: 解决了两个Base case后,如果两个数相等,返回True
        return n1.val == n2.val and out_nodes and in_nodes



965. Univalued Binary Tree

Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

Base Case: 当Node为空的时候,返回True

Recursive Rule :
向下索取:Subtree是否也是Uni-valued
向上返回:如果当前Value和Target Value相等返回True

class Solution(object):
    def isUnivalTree(self, root):
        if not root: return True
        return self.dfsHelper(root.val, root)
    
    def dfsHelper(self, target, root):
        if not root: return True
        left = self.dfsHelper(target, root.left)
        right = self.dfsHelper(target, root.right)
        return root.val == target and left and right



226. Invert Binary Tree

Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

Base Case: 当任意Node触底,比较该Node和另一个传递下来的Node的关系
如果都为空,返回True,如果不平衡返回False

Recursive Rule:
传递:左右孩子
索取:左右孩子的Reference,用于之后交换
返回:Node的Reference,用于上一层的左右交换。

class Solution(object):
    def invertTree(self, root):
        if not root: return
        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left = right ; root.right = left
        return root

@Everfighting
Copy link

楼主加油!之前想跟着您刷题的,后面工作太忙跟不上了。您这样努力刷题,一定会有好结果的!不要放弃!

@lcxcbe
Copy link

lcxcbe commented Mar 14, 2019

加油,之前断断续续刷过,最近看到楼主在leetcode上的题解,追到了github,受益匪浅。还在想楼主是否已经拿到offer了,因为已经有一段时间没有更新了。公瑾加油,肯定没问题的。

@tech-cow
Copy link
Owner Author

tech-cow commented Mar 14, 2019

造树的一类题

@tech-cow
Copy link
Owner Author

BFS + 层级遍历

102. Binary Tree Level Order Traversal

from collections import deque
class Solution:
    def levelOrder(self, root):
        if not root: return []
        queue, res = deque([root]), []
        
        while queue:
            cur_level, size = [], len(queue)
            for i in range(size):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                cur_level.append(node.val)
            res.append(cur_level)
        return res

993. Cousins in Binary Tree

from collections import deque
class Solution(object):
    def isCousins(self, root, x, y):
        queue = deque([root])
        while queue:
            size, temp = len(queue), {}
            for i in range(size):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                    temp[node.left.val] = node.val
                if node.right:
                    queue.append(node.right)
                    temp[node.right.val] = node.val
                    
            if x in temp and y in temp:
                return temp[x] == temp[y]
            
        return False

@HaoyangFan
Copy link

楼主加油!今年秋天就要作为new graduate开始找全职了,希望能通过参考您刷题的足迹拿到理想的offer

@tech-cow tech-cow closed this as completed Aug 7, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants