144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
题意:二叉树的先序遍历
代码如下:
//法一 // var preorderTraversal = function(root) { // let res=[]; // helper(root,res); // return res; // }; // var helper=function(root,res){ // if(!root) return ; // res.push(root.val); // helper(root.left,res); // helper(root.right,res); // } //法二 var preorderTraversal = function(root) { if(!root) return []; let res=[],s=[]; s.push(root); while(s.length>0){ let t=s.pop(); res.push(t.val); if(t.right) s.push(t.right); if(t.left) s.push(t.left); } return res; };