Swift.二叉树的前序遍历

cubegao 2015-05-24 PM 443℃ 0条
import Foundation

class MyTreeNodeSolution {
    
    //递归
    func preorderTraversal(_ root: TreeNode?,_ n: inout [Int]) {
        
        if root == nil {
            return
        }
        
        n.append(root!.val)
        preorderTraversal(root?.left, &n)
        preorderTraversal(root?.right, &n)
    }
    
    //非递归
    func preorderTraversal2(_ root: TreeNode?) -> [Int] {
        
        var node = root
        var stack = [TreeNode?]()
        var res = [Int]()
        
        while !stack.isEmpty || node != nil {
            
            if node != nil {
                res.append(node!.val)
                stack.append(node)
                node = node?.left
            }else {
                node = stack.removeLast()?.right
            }
        }
        
        return res
    }
}

算法思想:前序遍历:根结点 ---> 左子树 ---> 右子树

github地址:https://github.com/cubegao/LeetCode

标签: 算法

非特殊说明,本博所有文章均为博主原创。

评论啦~