leetcode94 Binary Tree Inorder Traversal

 1 """
 2 Given a binary tree, return the inorder traversal of its nodes' values.
 3 Example:
 4 Input: [1,null,2,3]
 5    1
 6     \
 7      2
 8     /
 9    3
10 Output: [1,3,2]
11 """
12 """
13 中序遍历题
14 解法一递归
15 """
16 class TreeNode:
17     def __init__(self, x):
18         self.val = x
19         self.left = None
20         self.right = None
21 
22 class Solution1:
23     def inorderTraversal(self, root):
24         if root == None:
25             return []
26         else:
27             List = []
28             self.order(root, List)  #bug,刚开始没有把List传进去
29         return List
30     def order(self, root, List):
31         if root.left:
32             self.order(root.left, List)
33         List.append(root.val)
34         if root.right:
35             self.order(root.right, List)
36 """
37 解法二:非递归
38 栈 思路:
39 (1)树先一直向左走到叶节点并将沿途的结点入栈 ;
40 (2)然后向右走一步,重复第一步操作。
41 注意要将沿途的节点进行入栈
42 """
43 class TreeNode:
44     def __init__(self, x):
45         self.val = x
46         self.left = None
47         self.right = None
48 class Solution2(object):
49     def inorderTraversal(self, root):
50         """
51         :type root: TreeNode
52         :rtype: List[int]
53         """
54         if root == None:
55             return []
56         List = []
57         stack = []
58         while root or stack:
59             if root:
60                 stack.append(root)
61                 root = root.left
62             else:
63                 root = stack.pop(-1)
64                 List.append(root.val)
65                 root = root.right
66         return List
67 if __name__ == '__main__':
68     S = Solution2()
69     l1 = TreeNode(1)
70     l2 = TreeNode(2)
71     l3 = TreeNode(3)
72     l4 = TreeNode(4)
73     l5 = TreeNode(5)
74     l6 = TreeNode(6)
75     l7 = TreeNode(7)
76     root = l1
77     l1.left = l2
78     l1.right = l3
79     l2.left = l4
80     l2.right = l5
81     l3.left = l6
82     l3.right = l7
83     print(S.inorderTraversal(root))

 

posted @ 2020-02-13 22:20  yawenw  阅读(98)  评论(0编辑  收藏  举报