比如上图正常的一个满节点,A:根节点、B:左节点、C:右节点,前序顺序是ABC(根节点排最先,然后同级先左后右);中序顺序是BAC(先左后根最后右);后序顺序是BCA(先左后右最后根)。
先(根)序遍历(根左右):A B D H E I C F J K G A B C以ABC作为根节点继续 遍历
中(根)序遍历(左根右) : D H B E I A J F K C G
后(根)序遍历(左右根) : H D I E B J K F G C A
解法一:递归
「二叉树的先序遍历」的思路是:先访问根结点,再访问左子树,最后访问右子树;
「二叉树的中序遍历」的思路是:先访问左子树,再访问根结点,最后访问右子树;
「二叉树的后序遍历」的思路是:先访问左子树,再访问右子树,最后访问根结点;
下图以「先序遍历」为例进行展示:
代码如下:
/*
* 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 ) {
let arr1 = [];
let arr2 = [];
let arr3 = [];
return [pre(root,arr1),mid(root,arr2),next(root,arr3)];
}
function pre(root, arr1){
if(root ==null) return root;
arr1.push(root.val)
pre(root.left, arr1)
pre(root.right, arr1)
return arr1
}
function mid(root, arr2){
if(root ==null) return root;
mid(root.left, arr2)
arr2.push(root.val)
mid(root.right, arr2)
return arr2
}
function next(root, arr3){
if(root ==null) return root;
next(root.left, arr3)
next(root.right, arr3)
arr3.push(root.val)
return arr3
}
module.exports = {
threeOrders : threeOrders
};