본문 바로가기
Algorithm/LeetCode

Traversing Tree (recursive, iterative)

by HaningYa 2021. 1. 18.
728x90
  • Tree traverse 할때 iterative 하게 하려면
  • Stack 사용
  • level traverse 의 경우 Queue 사용
  • Binary Tree 일 경우 node nil 로 loop 가능
 

N-ary Tree Preorder Traversal - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/**
 * Definition for a Node.
 * public class Node {
 *     public var val: Int
 *     public var children: [Node]
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.children = []
 *     }
 * }
 */

class Solution {
    var ans : [Int] = []
    func preorder(_ root: Node?) -> [Int] {
    	//recursive
    	// dfs(root)
        
        //iterative
        guard let root = root else {
            return []
        }
        var stack : [Node] = []
        stack.append(root)
        while !stack.isEmpty {
            let node = stack.removeLast()
            ans.append(node.val)
            for node in node.children.reversed() {
                stack.append(node)
            }
        }
        return ans
    }
    func dfs(_ node : Node?)  {
        guard let node = node else {
            return 
        }
        ans.append(node.val)
        for child in node.children {
            dfs(child)
        }
    }
}
728x90

'Algorithm > LeetCode' 카테고리의 다른 글

876. Middle of the Linked List  (0) 2021.01.28
이진탐색  (0) 2021.01.19
LeetCode - Remove Duplicates from Sorted Array  (0) 2020.09.11
LeetCode - Fibonacci Number, Climbing Stairs  (0) 2020.09.10
LeetCode - Pascal's Triangle II  (0) 2020.09.10

댓글