美文网首页
中序遍历

中序遍历

作者: hustyanye | 来源:发表于2019-07-15 22:04 被阅读0次

    https://leetcode-cn.com/problems/binary-tree-inorder-traversal/submissions/

    中序遍历的递归实现还是很容易的,自己在函数里面写过help,再递归去调用即可

    class Solution(object):
        def inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            arr = []
            def help(root):
                if not root:
                    return 
                help(root.left)
                arr.append(root.val)
                help(root.right)
            help(root)
            return arr
    

    非递归调用的时候,需要自己用一个队列模拟递归操作
    先找到最左的节点,不停的push到队列中,然后取出队列末端元素输出,在遍历其右子树即可

    class Solution(object):
        def inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            arr = []
            queue = []
            tmp = root
            while tmp or queue:
                while tmp:
                    queue.append(tmp)
                    tmp = tmp.left
                last = queue.pop()
                arr.append(last.val)
                tmp = last.right
                
            return arr
    

    相关文章

      网友评论

          本文标题:中序遍历

          本文链接:https://www.haomeiwen.com/subject/gltakctx.html