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
  • 相关阅读:
    poj 2002 Squares 几何二分 || 哈希
    hdu 1969 Pie
    hdu 4004 The Frog's Games 二分
    hdu 4190 Distributing Ballot Boxes 二分
    hdu 2141 Can you find it? 二分
    Codeforces Round #259 (Div. 2)
    并查集
    bfs
    二维树状数组
    一维树状数组
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5455845.html
Copyright © 2011-2022 走看看