您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法
二叉树的中序遍历(图文)
第十三双眼睛2023-11-26【数据结构与算法】人已围观
简介二叉树的中序遍历
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
思路:用递归的思路,对于没一个节点,先处理它的左子树,然后处理当前节点,再处理右子树。代码如下:
public static void test(TreeNode root,List<Integer> list) { if (root == null) { return; } // 中序遍历,先输出左子节点 if (root.left != null) { test(root.left, list); } // 然后输出根节点 list.add(root.val); // 最后输出右子节点 if (root.right != null) { test(root.right, list); } } |
public static List<Integer> method1(TreeNode root) { List<Integer> list = new ArrayList<>(); test(root, list); return list; } |
Tags:
很赞哦! ()
上一篇:删除排序链表中的重复元素(图文)
下一篇:相同的树(图文)