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
  • 相关阅读:
    2019/9/10
    2019/9/9
    软件课程设计(21)
    软件课程设计(20)
    软件课程设计(19)
    软件课程设计(18)
    软件课程设计(17)
    软件课程设计(16)
    数风流人物,还看今朝
    峰回路转二十四天
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5455845.html
Copyright © 2011-2022 走看看