zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):094 Binary Tree Inorder Traversal

    题目来源


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

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

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,3,2].


    题意分析


    Input:tree

    Output: inorder traversal

    Conditions:中序遍历,要非递归


    题目思路


    非递归实现


    AC代码(Python)

     1 # Definition for a  binary tree node
     2 # class TreeNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution:
     9     # @param root, a tree node
    10     # @return a list of integers
    11     def iterative_inorder(self, root, list):
    12         stack = []
    13         while root or stack:
    14             if root:
    15                 stack.append(root)
    16                 root = root.left
    17             else:
    18                 root = stack.pop()
    19                 list.append(root.val)
    20                 root = root.right
    21         return list
    22                 
    23     def recursive_inorder(self, root, list):
    24         if root:
    25             self.inorder(root.left, list)
    26             list.append(root.val)
    27             self.inorder(root.right, list)
    28         
    29     def inorderTraversal(self, root):
    30         list = []
    31         self.iterative_inorder(root, list)
    32         return list
  • 相关阅读:
    网络请求Request
    HTML元素
    你所不知的 CSS ::before 和 ::after 伪元素用法
    DOM理解
    为什么你应该尝试全栈
    程序员菜鸟的常用网站
    前端零基础学习提纲
    JavaScript,调用函数的5种方法
    json数据转化及应用
    浅谈ajax中的GET和POST
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5455845.html
Copyright © 2011-2022 走看看