/** * 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 { Stack<int> S = new Stack<int>(); private void preNode(TreeNode node) { if (node != null) { S.Push(node.val); if (node.left != null) { preNode(node.left); } if (node.right != null) { preNode(node.right); } } } public IList<int> PreorderTraversal(TreeNode root) { preNode(root); var list = S.Reverse().ToList(); return list; } }
https://leetcode.com/problems/binary-tree-preorder-traversal/#/description