# 描述

分别按照二叉树先序, 中序和后序打印所有的节点。

示例1

输入:
{1,2,3}

返回值:
[[1,2,3],[2,1,3],[2,3,1]]
1
2
3
4
5

这道题目和leetcode的区别是返回的是二维数组。

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 */
function threeOrders( root ) {
  const preRes = [];
  function preOrder(root) {
     if(root) {
       preRes.push(root.val);
       preOrder(root.left);
       preOrder(root.right);
     }
  }
  const inRes = [];
  function inOrder(root) {
    if (root) {
      inOrder(root.left)
      inRes.push(root.val)
      inOrder(root.right)
    }
  }
  const postRes = []
  function postOrder(root) {
    if(root) {
      postOrder(root.left)
      postOrder(root.right)
      postRes.push(root.val)
    }
  }
  // write code here
  preOrder(root)
  inOrder(root)
  postOrder(root)
  return [preRes, inRes, postRes]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

# 1220复习

  • 1、树这种数据结构天然具有递归的特性,这道题目在这个场景下,需要注意执行的顺序和递归的终止条件。

# 0214复习

  • 1 还是没有做出来,这道题目本身的思想并不是很复杂,难度在于对于返回值结构的构造。
最后更新时间: 2/15/2022, 10:13:32 AM