[BackTracking]094 Binary Tree Inorder Traversal

  • 分类:BackTracking

  • 考察知识点:BackTracking 二叉树(Binary Tree)

  • 最优解时间复杂度:**BackTracking:O(???) ** BackTracking不好求 **Stack:O(n) **

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

代码:

解法1(BackTracking):

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

class Solution:
    
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """ 
        res=[]
        
        if root==None:
            return res
        self.Traversal(root,res)
        return res
        
    def Traversal(self,root,res):
        if root == None:
            return
        self.Traversal(root.left,res)
        res.append(root.val)
        self.Traversal(root.right,res)

解法2(Stack):

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

class Solution:
    
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """ 
        res=[]
        
        if root==None:
            return res
        
        stack=[]
        pointer=root
        while(pointer!=None or len(stack)!=0):
            while pointer!=None:
                stack.append(pointer)
                pointer=pointer.left
            pointer=stack.pop()
            res.append(pointer.val)
            pointer=pointer.right
        return res

讨论:

1.考一个二叉树的遍历,左中右的遍历
2.这道题有两种方法做这个题,一个是用Stack,一个是用回溯

  1. inorder traversal 记一下这个名词是左中右遍历
[BackTracking]094 Binary Tree Inorder Traversal_第1张图片
BackTracking
[BackTracking]094 Binary Tree Inorder Traversal_第2张图片
Stack

你可能感兴趣的:([BackTracking]094 Binary Tree Inorder Traversal)