美文网首页
94. 二叉树的中序遍历

94. 二叉树的中序遍历

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-16 15:03 被阅读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
}

相关文章

网友评论

      本文标题:94. 二叉树的中序遍历

      本文链接:https://www.haomeiwen.com/subject/sasgehtx.html