[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

 

posted @ 2016-05-03 17:39  loadofleaf  Views(261)  Comments(0Edit  收藏  举报