var preorderTraversal = function(root) { let white = 0, black = 1 let stack = [[white, root]] let result = [] while(stack.length > 0) { let [color, node] = stack.pop() if(!node) continue if (color == white) { stack.push([white, node.right]) stack.push([white, node.left]) stack.push([black, node]) }else{ result.push(node.val) } } return result };
中序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var inorderTraversal = function(root) { let white = 0, black = 1 let stack = [[white, root]] let result = [] while(stack.length > 0) { let [color , node] = stack.pop() if (!node) { continue } if(color == white) { stack.push([white, node.right]) stack.push([black, node]) stack.push([white, node.left]) }else{ result.push(node.val) } } return result };
后序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var postorderTraversal = function(root) { let white = 0, black = 1 let stack = [[white, root]] let result = [] while(stack.length > 0) { let [color,node] = stack.pop() if (!node) continue if (color == white) { stack.push([black,node]) stack.push([white, node.right]) stack.push([white, node.left]) }else { result.push(node.val) } } return result };