LeetCode -- Binary Tree Preorder Traversal

来源:互联网 发布:气象数据下载 编辑:程序博客网 时间:2024/04/29 18:25
题目描述:


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].


思路:


题目很直白,就是树的先序遍历。直接实现就可以了。


实现代码:




/** * 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)     {        var ret = new List<int>();    Travel(root, ref ret);        return ret;    }private void Travel(TreeNode current, ref List<int> result){if(current == null){return ;}result.Add(current.val);Travel(current.left, ref result);Travel(current.right, ref result);}}


1 0
原创粉丝点击