[LeetCode][JavaScript]Binary Tree Inorder Traversal

Binary Tree Inorder Traversal

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

For example:
Given binary tree {1,#,2,3},

   1
    
     2
    /
   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

https://leetcode.com/problems/binary-tree-inorder-traversal/


树的中序遍历,把节点按照右中左的顺序塞到栈中。

因为js的数组可以放不同类型,放中间的时候放入的是val,两边放入TreeNode对象。

遇到val就直接放入结果中;遇到TreeNode节点,继续按照右中左的顺序入栈。

Binary Tree Preorder Traversal:

http://www.cnblogs.com/Liok3187/p/4805834.html

Binary Tree Postorder Traversal:

http://www.cnblogs.com/Liok3187/p/4822303.html

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {number[]}
11  */
12 var inorderTraversal = function(root) {
13     var stack = [], res = [], top;
14     if(root){
15         stack.push(root);
16     }
17 
18     while(stack.length !== 0){
19         top = stack.pop();
20         if(typeof top === "number"){
21             res.push(top);
22         }else{
23             if(top.right){
24                 stack.push(top.right);
25             }
26             stack.push(top.val);
27             if(top.left){
28                 stack.push(top.left);
29             }
30         }
31     }
32     return res;
33 };
原文地址:https://www.cnblogs.com/Liok3187/p/4808974.html