二叉树相关编程题 Python

重建二叉树

class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre or not tin:
            return None
        root = TreeNode(pre.pop(0))
        root_local = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre[:root_local+1], tin[:root_local])
        root.right = self.reConstructBinaryTree(pre[root_local:], tin[root_local+1:])
        return root

 

树的子结构

class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        result = False
        if pRoot1!=None and pRoot2!=None:
            if pRoot1.val == pRoot2.val:
                result = self.isSameTree(pRoot1, pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.left, pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.right, pRoot2)
        return result
         
    def isSameTree(self, root1, root2):
        if root2 == None:
            return True
        if root1 == None:
            return False
        if root1.val != root2.val:
            return False
        return self.isSameTree(root1.left, root2.left) and self.isSameTree(root1.right, root2.right)

 

二叉树的镜像

class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if not root:
            return None
        root.left, root.right = root.right, root.left
        self.Mirror(root.left)
        self.Mirror(root.right)

 

二叉搜索树的后序遍历序列

class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        length = len(sequence)
        if length == 0:
            return False
        if length == 1:
            return True
        
        root = sequence[-1]
        
        left = 0
        while sequence[left] < root:
            left += 1
        
        for j in range(left,length-1):
            if sequence[j] < root:
                return False
        
        return self.VerifySquenceOfBST(sequence[:left]) or self.VerifySquenceOfBST(sequence[left:length-1])

 

二叉树中和为某一值的路径

class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def FindPath(self, root, expectNumber):
        # write code here
        if not root:
            return []
        if root and not root.left and not root.right and root.val == expectNumber:
            return [[root.val]]
        res = []
        left = self.FindPath(root.left, expectNumber-root.val)
        right = self.FindPath(root.right, expectNumber-root.val)
        for i in left+right:
            res.append([root.val]+i)
        return res
    

二叉搜索树与双向链表

class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        if not pRootOfTree:
            return None
        pRoot = pRootOfTree
        self.node_arr = []
        self.midOrder(pRoot)
        for i in range(1, len(self.node_arr)):
            self.node_arr[i].left = self.node_arr[i-1]
            self.node_arr[i-1].right = self.node_arr[i]
        return self.node_arr[0]
        
    def midOrder(self, root):
        if not root:
            return None
        self.midOrder(root.left)
        self.node_arr.append(root)
        self.midOrder(root.right)

 

二叉树的深度

class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if not pRoot:
            return 0
        
        return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1
 

平衡二叉树

class Solution:
    def IsBalanced_Solution(self, pRoot):
        # write code here
        if not pRoot:
            return True
        left = self.deepOfTree(pRoot.left)
        right = self.deepOfTree(pRoot.right)
        if abs(left-right) > 1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
    
    def deepOfTree(self, root):
        if not root:
            return 0
        left = self.deepOfTree(root.left)
        right = self.deepOfTree(root.right)
        return max(left, right) + 1

 

从上往下打印二叉树

class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if not root:
            return []
        queue = [root]
        res = []
        while len(queue) > 0:
            node = queue.pop(0)
            res.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return res

 

二叉树的下一个结点

class Solution:
    def GetNext(self, pNode):
        # write code here
        if not pNode:
            return pNode
        
        if pNode.right:
            right_root = pNode.right
            while right_root.left:
                right_root = right_root.left
            return right_root
        
        cur_node = pNode
        while cur_node.next:
            father_node = cur_node.next
            if father_node.left == cur_node:
                return father_node
            cur_node = father_node

 

对称的二叉树

class Solution:
    def isSymmetrical(self,pRoot):
        # write code here
        return self.isSameTree(pRoot,pRoot)
         
    def isSameTree(self,root1,root2):
        if root1 == None and root2 == None:
            return True
        if root1 == None or root2 == None:
            return False
        if root1.val != root2.val:
            return False
         
        return self.isSameTree(root1.left,root2.right) and self.isSameTree(root1.right,root2.left)

 

按之字形顺序打印二叉树

class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        results = []
        level = 1
        queue = [pRoot]
        while len(queue) > 0:
            nodes = []      # 存储下一层的节点
            result = []     # 存储该层的结果
            for root in queue:
                if root != None:
                    result.append(root.val)
                    if root.left:
                        nodes.append(root.left)
                    if root.right:
                        nodes.append(root.right)
            if level%2 == 0:   # 偶数层翻转
                result.reverse()
            if len(result) > 0:
                results.append(result)
            level += 1
            queue = nodes
        
        return results

 

把二叉树打印成多行

class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        results = []
        queue = [pRoot]
        while len(queue) > 0:
            result = []
            nodes = []
            for root in queue:
                result.append(root.val)
                if root.left:
                    nodes.append(root.left)
                if root.right:
                    nodes.append(root.right)
            results.append(result)
            queue = nodes
            
        return results

 

序列化二叉树

class Solution:
    def Serialize(self, root):
        # write code here
        if not root:
            return '#'
        return str(root.val) + ',' + self.Serialize(root.left) + ',' + self.Serialize(root.right)
        
    def Deserialize(self, s):
        # write code here
        root, index = self.deserialize(s.split(','), 0)
        return root
    
    def deserialize(self, s, index):
        if s[index] == '#':
            return None, index+1
        root = TreeNode(int(s[index]))
        index += 1
        root.left, index = self.deserialize(s, index)
        root.right, index = self.deserialize(s, index)
        return root, index

 

二叉搜索树的第k个结点、

class Solution:
    # 返回对应节点TreeNode
    def KthNode(self, pRoot, k):
        # write code here
        if not pRoot:
            return None
        self.res = []
        self.midOrder(pRoot)
        if k <=0 or k > len(self.res):
            return None
        else:
            return self.res[k-1]
        
    def midOrder(self, root):
        if not root:
            return None
        self.midOrder(root.left)
        self.res.append(root)
        self.midOrder(root.right)

 

序列化二叉树

class Solution:
    def Serialize(self, root):
        # write code here
        if not root:
            return '#'
        return str(root.val) + ',' + self.Serialize(root.left) + ',' + self.Serialize(root.right)
        
    def Deserialize(self, s):
        # write code here
        root, index = self.deserialize(s.split(','), 0)
        return root
    
    def deserialize(self, s, index):
        if s[index] == '#':
            return None, index+1
        root = TreeNode(int(s[index]))
        index += 1
        root.left, index = self.deserialize(s, index)
        root.right, index = self.deserialize(s, index)
        return root, index

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值