Created
March 6, 2021 12:10
-
-
Save MohammedALREAI/f32511f5c08e0855973d5dc6f3d7e5c6 to your computer and use it in GitHub Desktop.
145. Binary Tree Postorder Traversal leetcode typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* class TreeNode { | |
* val: number | |
* left: TreeNode | null | |
* right: TreeNode | null | |
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { | |
* this.val = (val===undefined ? 0 : val) | |
* this.left = (left===undefined ? null : left) | |
* this.right = (right===undefined ? null : right) | |
* } | |
* } | |
*/ | |
// [1,null,2,3] | |
function postorderTraversal(root: TreeNode | null): number[] { | |
if(!root){ | |
return []; | |
} | |
let res:number[]=[] | |
let stack=[] | |
stack.push(root); | |
while(stack.length>0){ | |
let current:TreeNode=stack.pop(); | |
res.push(current.val); | |
if(current.left!=null){ | |
stack.push(current.left); | |
} | |
if(current.right!=null){ | |
stack.push(current.right); | |
} | |
} | |
return res.reverse(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment