LeetCode-94.Binary Tree Inorder Traversal

来源:互联网 发布:上网控制软件破解版 编辑:程序博客网 时间:2024/05/16 11:21

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;        }



0 0
原创粉丝点击