94. 二叉树的中序遍历

2020-03-16  本文已影响0人  寂灭天骄小童鞋

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

//递归
var  result = [Int]()

func inorderTraversal(_ root: TreeNode?) -> [Int] {
    if root == nil {return []}
    //左子树
    inorderTraversal(root?.left)
    
    //节点
    result.append(root!.val)
    
    //右子树
    inorderTraversal(root?.right)
        
    return result
}

//迭代
func inorderTraversal(_ root: TreeNode?) -> [Int] {
    if root == nil {return []}
    var  result = [Int]()
    var  tmpStack = [TreeNode]()
    var curNode = root
    while curNode != nil || !tmpStack.isEmpty {
        while curNode != nil {
            tmpStack.append(curNode!)
            curNode = curNode?.left
        }
        curNode = tmpStack.popLast()
        result.append(curNode!.val)
        curNode = curNode?.right
    }
    return result
}

上一篇 下一篇

猜你喜欢

热点阅读