给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[2,1]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
提示:
- 树中节点数目在范围 [0, 100] 内
- -100 <= Node.val <= 100
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val, left, right) { 4 * this.val = (val===undefined ? 0 : val) 5 * this.left = (left===undefined ? null : left) 6 * this.right = (right===undefined ? null : right) 7 * } 8 */ 9 /** 10 * @param {TreeNode} root 11 * @return {number[]} 12 */ 13 14 //递归 15 var inorderTraversal = function(root) { 16 const res = []; //中序遍历左 根 右 17 const rec = (n) => { //rec是递归的英文recursion缩写 18 if(!n) return; 19 rec(n.left); 20 res.push(n.val); 21 rec(n.right); 22 }; 23 rec(root); 24 return res; 25 }; 26 27 //非递归 28 var inorderTraversal = function(root) { 29 const res = []; 30 const stack = []; 31 let p = root; //p指针 32 while( stack.length || p) { 33 while(p) { 34 stack.push(p); 35 p = p.left; 36 } 37 const n = stack.pop(); 38 res.push(n.val); 39 p = n.right; 40 } 41 return res; 42 };