[路飞]_LeetCode题145二叉树的后序遍历

159 阅读1分钟

题目描述

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]
1
2 / 3

输出: [3,2,1]

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/bi… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解思路

  1. 后序遍历是从底部最左侧叶子结点开始按照左右中的顺序逐级向上。
  2. 左子树的按照这个顺序遍历完再以该顺序遍历右子树所有节点。
  3. 最后遍历根节点。

题解代码

 * @lc app=leetcode.cn id=145 lang=javascript
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * 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) {
  let res = [];
  const postOrder = (root) => {
    if (!root) return;
    //后序遍历按照  左-->右-->中顺序
    postOrder(root.left);//先找左节点
    postOrder(root.right);//再找右节点
    res.push(root.val);//最后根节点
  }
  postOrder(root);
  return res;
  
};
// @lc code=end