zoukankan      html  css  js  c++  java
  • 94. Binary Tree Inorder Traversal

    94. Binary Tree Inorder Traversal

    Given a binary tree, return the inorder traversal of its nodes' values.

    For example:
    Given binary tree [1,null,2,3],

       1
        
         2
        /
       3
    

    return [1,3,2].

    该题是做树的中序遍历,下面分别是递归解法和非递归解法:

    递归解法:

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

     非递归解法:

    class Solution(object):
        def inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if not root:
                return []
            stack = []
            node = root
            result = []   
            while node or len(stack) > 0:
                while node:
                    stack.append(node)
                    node = node.left
                node = stack.pop()
                result.append(node.val)
                node = node.right
            return result
  • 相关阅读:
    charles使用
    断言
    JDBC Request
    HTTP请求建立一个测试计划
    利用badboy进行脚本录制
    接口测试用例
    Monkey常用命令
    charles安装与使用
    celery配置与基本使用
    图片验证码接口
  • 原文地址:https://www.cnblogs.com/bubbleStar/p/6359032.html
Copyright © 2011-2022 走看看