二叉樹的中序遍歷(非遞歸)


中序遍歷是先遍歷左子樹,在自身,再遍歷右子樹,

非遞歸實現的方法,一直遍歷左節點,然后出棧,在遍歷右節點

 

# 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]
        """
        if root ==None:
            return []
        stack=[]
        result=[]
        while (len(stack)!=0 or  root!=None):
            while root!=None:
                stack.append(root)
                root =root.left
            if len(stack)!=0:
                root=stack.pop()
                result.append(root.val)
                root =root.right
        return result

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM