LeetCode 94 [Binary Tree Inorder Traversal]

weixin_33727510發表於2015-10-22

原題

給出一棵二叉樹,返回其中序遍歷

給出二叉樹 {1,#,2,3}

   1
    \
     2
    /
   3

返回 [1,3,2]

解題思路

  • 方法一:遞迴,定義helper函式
  • 方法二:Divide & Conquer
  • 方法二:非遞迴
  • (操作一)每一次從當前節點開始(第一次是root節點)遍歷至最左節點,一次入棧。
  • (操作二)pop出棧一個node,node.val加入到結果,然後看該node有沒有右兒子
  • 有的話重複操作一
  • 沒有的話,繼續pop出棧一個node,重複操作二
  • 非遞迴解法可以體會一下另外一個題[Inorder Successor in Binary Search Tree]

完整程式碼

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 方法一
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        self.helper(root, res)
        return res
        
    def helper(self, root, result):
        if root != None:
            self.helper(root.left, result)
            result.append(root.val)
            self.helper(root.right, result)

# 方法二
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        result = []
        if root == None:
            return result
        result.append(root.val)
        
        # divide
        left = self.inorderTraversal(root.left)
        right = self.inorderTraversal(root.right)
        
        # conquer
        return left + result + right

# 方法三
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        stack = []
        result = []
        current = root
        while current != None or len(stack) != 0:
            while current != None:
                stack.append(current)
                current = current.left
            current = stack[-1];
            stack.pop();
            result.append(current.val);
            current = current.right;
        return result

相關文章