字节跳动 144. Binary Tree Preorder T
2020-07-16 本文已影响0人
苦庭
https://leetcode.com/problems/binary-tree-preorder-traversal/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let s = [];
let p = root;
let res = [];
while(p!=null || s.length!=0){
while(p!=null){
res.push(p.val);
s.push(p);
p = p.left;
}
if(s.length!=0){
p = s.pop();
p = p.right;
}
}
return res;
};
非递归方法重点要掌握先一路往左走(外while和内while),然后一边走一边入栈。接下来一路从底部往上走,如果能往上走(外while内if)就将指针切到右子节点去测试是否能更深一层走。