1. 程式人生 > 其它 >145. 二叉樹的後序遍歷

145. 二叉樹的後序遍歷

題目來源:145. 二叉樹的後序遍歷

/**
 * 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 postorderTraversal = function(root) { if (root === null) return []; let cur = root; let res = []; var addPath=(node) =>{ let arr = []; while(node != null){ arr.push(node.val); node = node.right; } return arr.reverse(); } while (cur) { let node
= cur.left; if (node !== null) { while (node !== null && node.right !== null && node.right !== cur) { node = node.right; } if (node.right === null) { node.right = cur; cur = cur.left; continue; } else { node.right = null
; res.push(...addPath(cur.left)); } } cur = cur.right; } res.push(...addPath(root)); return res; };

給定一個二叉樹,返回它的後序遍歷。

示例:

輸入: [1,null,2,3]  
   1
    \
     2
    /
   3 

輸出: [3,2,1]

進階:遞迴演算法很簡單,你可以通過迭代演算法完成嗎?