94. Binary Tree Inorder Traversal(js)

94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]
题意:中序遍历一颗树
代码如下:
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    var res=[];
    inorder(root,res);
    return res;
};
// 法一
function inorder(root,res){
    if(!root) return ;
    inorder(root.left,res);
    res.push(root.val);
    inorder(root.right,res);
}
// 法二
// var inorderTraversal=function(root){
//         var  res=[];
//         //栈  
//         var s=[];
//         var p = root;
    
//         while (p || s.length>0) {
//             //直至左节点为空,即没有左节点为止
//             while (p) {
//                 s.push(p);
//                 p = p.left;
//             }
//             //出栈,存放根节点
//             p = s.pop();
//             res.push(p.val);
//             p = p.right;
//         }
//         return res;
// }

猜你喜欢

转载自www.cnblogs.com/xingguozhiming/p/10707351.html