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 do it iteratively?
https://leetcode.com/problems/binary-tree-preorder-traversal/
The tree's first order traversal, does not recursively the way, maintains a stack, first plugs the right sub-tree, then Seizo the tree.
Recursion:
1 /**2 * Definition for a binary tree node.3 * Function TreeNode (val) {4 * This.val = val;5 * This.left = This.right = null;6 * }7 */8 /**9 * @param {TreeNode} rootTen * @return {number[]} One */ A varPreordertraversal =function(root) { - varres = []; - preorder (root); the returnRes; - - functionPreorder (node) { - if(Node && node.val!==undefined) { + Res.push (node.val); - if(Node.left!==NULL){ + preorder (node.left); A } at if(Node.right!==NULL){ - preorder (node.right); - } - } - } -};
Non-recursive:
1 /**2 * @param {TreeNode} root3 * @return {number[]}4 */5 varPreordertraversal =function(root) {6 varstack = [], res =[], Curr;7 if(Root && root.val!==undefined) {8 Res.push (root.val);9 if(Root.right!==NULL){Ten Stack.push (root.right); One } A if(Root.left!==NULL){ - Stack.push (root.left); - } the } - while(stack.length!== 0){ -Curr =Stack.pop (); - Res.push (curr.val); + if(Curr.right!==NULL){ - Stack.push (curr.right); + } A if(Curr.left!==NULL){ at Stack.push (curr.left); - } - } - returnRes; -};
[Leetcode] [JavaScript] Binary Tree Preorder Traversal