LeetCode-144.Binary Tree Preorder Traversal

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

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

   1
    \
     2
    /
   3

return [1,2,3].

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

/**
 * 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> PreorderTraversal(TreeNode root)
        {
            IList<int> list = new List<int>();
            Fun(list, root);
            return list;
        }

        public void Fun(IList<int> list,TreeNode node)
        {
            if (node!=null)
            {
                list.Add(node.val);
                Fun(list, node.left);
                Fun(list, node.right);
            }
        }
}

非递归解

public IList<int> PreorderTraversal(TreeNode root)
        {
            IList<int> list = new List<int>();
            if (root==null)
                return list;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.Push(root);
            TreeNode node;
            while (stack.Count>0)
            {
                node = stack.Pop();
                list.Add(node.val);
                if (node.right != null)
                    stack.Push(node.right);
                if (node.left != null)
                    stack.Push(node.left);
            }
            return list;
        }


你可能感兴趣的:(算法,tree)