题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
using System; using System.Collections.Generic; /* public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ public List<List<int>> threeOrders (TreeNode root) { // write code here if (root == null) return new List<List<int>>() { new List<int>(), new List<int>(), new List<int>() }; List<int> listLeft = new List<int>(); DGLeft(root, listLeft); List<int> listMiddle = new List<int>(); DGMiddle(root, listMiddle); List<int> listRight = new List<int>(); DGRight(root, listRight); // write code here return new List<List<int>>() { listLeft, listMiddle, listRight }; } public void DGLeft(TreeNode treeNode, List<int> listInt) { if (treeNode == null) return; listInt.Add(treeNode.val); DGLeft(treeNode.left, listInt); DGLeft(treeNode.right, listInt); } public void DGMiddle(TreeNode treeNode, List<int> listInt) { if (treeNode == null) return; DGMiddle(treeNode.left, listInt); listInt.Add(treeNode.val); DGMiddle(treeNode.right, listInt); } public void DGRight(TreeNode treeNode, List<int> listInt) { if (treeNode == null) return; DGRight(treeNode.left, listInt); DGRight(treeNode.right, listInt); listInt.Add(treeNode.val); } }