[LeetCode][JavaScript]Binary Tree Preorder Traversal
2015-09-13 22:56
651 查看
Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
https://leetcode.com/problems/binary-tree-preorder-traversal/
树的先序遍历,不递归的方式,维护一个栈,先塞右子树,再塞左子树。
Binary Tree Inorder Traversal:
/article/7171024.html
Binary Tree Postorder Traversal:
/article/7171025.html
递归:
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number[]} */ var preorderTraversal = function(root) { var res = []; preorder(root); return res; function preorder(node){ if(node && node.val !== undefined){ res.push(node.val); if(node.left !== null){ preorder(node.left); } if(node.right !== null){ preorder(node.right); } } } };
非递归:
/** * @param {TreeNode} root * @return {number[]} */ var preorderTraversal = function(root) { var stack = [], res = [], curr; if(root){ stack.push(root); } while(stack.length !== 0){ curr = stack.pop(); res.push(curr.val); if(curr.right !== null){ stack.push(curr.right); } if(curr.left !== null){ stack.push(curr.left); } } return res; };
相关文章推荐
- 配置JSDoc的默认模板
- js用addeventlistener绑定事件,阻止默认事件。
- 【学习笔记】JavaScript中,构造函数、原型对象和实例的关系
- 09-13 网页计算器案例
- JavaScript的垃圾回收机制
- JavaScript的垃圾回收机制
- js节点操作
- Javascript高级程序设计第十四章(表单)
- Javascript中没有块级作用域(模仿)
- Javascript中没有块级作用域(模仿)
- JS BOM(浏览器对象)
- JavaScript设计模式——单体模式
- 正确理解javascript当中的面向对象
- js 杂碎
- this是谁?
- js的document.write 输出内容把网页内容全部冲刷掉了
- JavaScript设计模式之----组合模式
- JavaScript设计模式之----组合模式
- JS函数修改html的元素内容,及修改属性内容
- JS面向对象