LeetCode-94.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?
confused what  "{1,#,2,3}"  means? > read more on how binary tree is serialized on OJ.
/**  * Definition for a binary tree node.  * public class TreeNode {  *     public int val;  *     public TreeNode left;  *     public TreeNode right;  *     public TreeNode(int x) { val = x; }  * }  */
再帰
public class Solution 
{
   public IList<int> InorderTraversal(TreeNode root)
        {
            IList<int> list = new List<int>();
            Fun(list, root);
            return list;
        }

        private void Fun(IList<int> list, TreeNode root)
        {
            if (root == null)
                return;
            Fun(list, root.left);
            list.Add(root.val);
            Fun(list, root.right);
        }
}
非再帰
public IList<int> InorderTraversal(TreeNode root)
        {
            IList<int> list = new List<int>();
            if (root == null)
                return list;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode node=root;
            while (node!=null||stack.Count>0)
            {
                while (node!=null)
                {
                    stack.Push(node);
                    node = node.left;
                }
                node = stack.Pop();
                list.Add(node.val);
                node = node.right;
            }
            return list;
        }