1. 前序遍历
1.1 递归
var preorderTraversal = function ( root ) { let result = [ ] traversal ( root, result) return result
} ; function traversal ( root, res ) { if ( root == null ) return res. push ( root. val) traversal ( root. left, res) traversal ( root. right, res)
}
1.2 迭代
var preorderTraversal = function ( root ) { if ( root == null ) return [ ] let result = [ ] let stash = [ root] while ( stash. length) { const curNode = stash. pop ( ) result. push ( curNode. val) if ( curNode. right) stash. push ( curNode. right) if ( curNode. left) stash. push ( curNode. left) } return result
} ;
2. 中序遍历
2.1 递归
var inorderTraversal = function ( root ) { let result = [ ] let traversal = ( node, res ) => { if ( node == null ) return traversal ( node. left, res) res. push ( node. val) traversal ( node. right, res) } traversal ( root, result) return result
} ;
2.2 迭代
var inorderTraversal = function ( root ) { let result = [ ] let stash = [ ] let node = rootwhile ( node || stash. length) { while ( node) { stash. push ( node) node = node. left} node = stash. pop ( ) result. push ( node. val) node = node. right} return result
} ;
3. 后序遍历
3.1 递归
var postorderTraversal = function ( root ) { let result = [ ] let traversal = ( node, res ) => { if ( node == null ) return traversal ( node. left, res) traversal ( node. right, res) res. push ( node. val) } traversal ( root, result) return result
} ;
3.2 迭代
var postorderTraversal = function ( root ) { if ( ! root) return [ ] let result = [ ] let stash = [ root] while ( stash. length) { let curNode = stash. pop ( ) result. unshift ( curNode. val) if ( curNode. left) stash. push ( curNode. left) if ( curNode. right) stash. push ( curNode. right) } return result
} ;