二叉树遍历

第二种写法
前序遍历

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        result = []
        st= []
        if root:
            st.append(root)
        while st:
            node = st.pop()
            if node != None:
                if node.right: #右
                    st.append(node.right)
                if node.left: #左
                    st.append(node.left)
                st.append(node) #中
                st.append(None)
            else:
                node = st.pop()
                result.append(node.val)
        return result

中序遍历

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        result = []
        st = []
        if root:
            st.append(root)
        while st:
            node = st.pop()
            if node != None:
                if node.right: #添加右节点(空节点不入栈)
                    st.append(node.right)
                
                st.append(node) #添加中节点
                st.append(None) #中节点访问过,但是还没有处理,加入空节点做为标记。
                
                if node.left: #添加左节点(空节点不入栈)
                    st.append(node.left)
            else: #只有遇到空节点的时候,才将下一个节点放进结果集
                node = st.pop() #重新取出栈中元素
                result.append(node.val) #加入到结果集
        return result

后序遍历

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        result = []
        st = []
        if root:
            st.append(root)
        while st:
            node = st.pop()
            if node != None:
                st.append(node) #中
                st.append(None)
                
                if node.right: #右
                    st.append(node.right)
                if node.left: #左
                    st.append(node.left)
            else:
                node = st.pop()
                result.append(node.val)
        return result

第一种

    def pre_traversal(self):
        """method of traversing BiTree in pre-order"""
        if self.root is None:
            return None
        else:
            node_stack = list()
            output_list = list()
            node = self.root
            while node is not None or len(node_stack):
                # if node is None which means it comes from a leaf-node' right,
                # pop the stack and get it's right node.
                # continue the circulating like this
                if node is None:
                    node = node_stack.pop().right
                    continue
                #  save the front node and go next when left node exists
                while node.left is not None:
                    node_stack.append(node)
                    output_list.append(node.get_element())
                    node = node.left
                output_list.append(node.get_element())
                node = node.right
        return output_list

    def in_traversal(self):
        """method of traversing BiTree in in-order"""
        if self.root is None:
            return None
        else:
            node_stack = list()
            output_list = list()
            node = self.root
            while node is not None or len(node_stack):
                # if node is None which means it comes from a leaf-node' right,
                # pop the stack and get it's right node.
                # continue the circulating like this
                if node is None:
                    node = node_stack.pop()
                    # in in-order traversal, when pop up a node from stack , save it
                    output_list.append(node.get_element())
                    node = node.right
                    continue
                # go-next when left node exists
                while node.left is not None:
                    node_stack.append(node)
                    node = node.left
                # save the the last left node
                output_list.append(node.get_element())
                node = node.right
        return output_list

    def post_traversal1(self):
        """method of traversing BiTree in in-order"""
        if self.root is None:
            return None
        else:
            node_stack = list()
            output_list = list()
            node = self.root
            while node is not None or len(node_stack):
                # if node is None which means it comes from a leaf-node' right,
                # pop the stack and get it's right node.
                # continue the circulating like this
                if node is None:
                    visited = node_stack[-1]["visited"]
                    # in in-order traversal, when pop up a node from stack , save it
                    if visited:
                        output_list.append(node_stack[-1]["node"].get_element())
                        node_stack.pop(-1)
                    else:
                        node_stack[-1]["visited"] = True
                        node = node_stack[-1]["node"]
                        node = node.right
                    continue
                # go-next when left node exists
                while node.left is not None:
                    node_stack.append({"node": node, "visited": False})
                    node = node.left
                # save the the last left node
                output_list.append(node.get_element())
                node = node.right
        return output_list

二叉树建立
在这里插入图片描述

#coding=utf-8
 
class TreeNode(object):
    def __init__(self,data=None,left=None,right=None):
        self.data = data
        self.left = left
        self.right = right
 
    # 这一步是在每次调用某个结点时,自动调用.data的方法
    def __str__(self):
        return str(self.data)
 
# 方法一
A, B, C, D, E, F, G, H, I = [TreeNode(x) for x in 'ABCDEFGHI']
A.left, A.right = B, C
B.right = D
C.left, C.right = E, F
E.left = G
F.left,F.right = H, I
print C.right
 
# 方法二
A = TreeNode('A','B','C')
B = TreeNode('B',None,'D')
C = TreeNode('C','E','F')
E = TreeNode('E','G',None)
F = TreeNode('F','H','I')
print C.right

层序

def PrintFromTopToBottom(self, root):
        array = []
        result = []
        if root == None:
            return result
 
        array.append(root)
        while array:
            newNode = array.pop(0)
            result.append(newNode.val)
            if newNode.left != None:  
                array.append(newNode.left)
            if newNode.right != None:
                array.append(newNode.right)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值