開放世界冒險探索遊戲《山上的宮殿》上架Steam
阿新 • • 發佈:2021-11-22
給你二叉樹的根節點 root ,返回它節點值的前序遍歷。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航import java.util.ArrayList; import java.util.Collections; import java.util.List; class Solution { public List<Integer> preorderTraversal(TreeNode root) { if (root == null) { return Collections.emptyList(); } List<Integer> ret = new ArrayList<>(); TreeNode cur = root; while (cur != null) { TreeNode mostRight = cur.left; if (mostRight != null) { while (mostRight.right != null && mostRight.right != cur) { mostRight = mostRight.right; } if (mostRight.right == null) { ret.add(cur.val); mostRight.right = cur; cur = cur.left; continue; } else { mostRight.right = null; } } else { ret.add(cur.val); } cur = cur.right; } return ret; } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }