思路:将p入栈并访问p.val,遍历左子树;遍历完左子树返回时,栈顶元素应为p,出栈,再先序遍历p的右子树。
代码:
/** * 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) { if(root==null){ return []; } if(root.left==null&&root.right==null){ return [root.val]; } var p=root,result=[],stack=[]; while(p||stack.length!=0){ if(p!=null){ stack.push(p); result.push(p.val); p=p.left; }else{ p=stack.pop(); p=p.right; } } return result; };