Moment For Technology

LeetCode-144- Preorder traversal of a binary tree

Posted on Aug. 10, 2023, 12:40 p.m. by Wendy Haynes
Category: java Tag: java algorithm leetcode Binary tree LeetCode Personal Problem Solving Summary

Preorder traversal of a binary tree

Given the root node of the binary tree, return the pre-order traversal of its node values.

See the LeetCode website for an example.

Source: LeetCode Link: Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: Recursion

Initialize a result set result, then recursively process it in the following order:

  • First, place the root node's value in result.
  • Then put the processing result of root node's left subtree into result;
  • Finally, put the processing result of the right subtree of root node into result;
  • When root is empty, an empty result is returned.

Finally, the result set Result is returned, which is the preorder traversal result of the tree.

Note: It is similar to the middle order traversal process, refer to the middle order traversal of leetcode-094 - binary tree.

import java.util.ArrayList; import java.util.List; public class LeetCode_144 { public static ListInteger preorderTraversal(TreeNode root) { if (root == null) { return new ArrayList(); } ListInteger result = new ArrayList(); result.add(root.val); result.addAll(preorderTraversal(root.left)); result.addAll(preorderTraversal(root.right)); return result; } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); root.right.left = new TreeNode(3); for (Integer integer : preorderTraversal(root)) { System.out.print(integer + " "); }}}
【 Daily Message 】 Every morning, remember to tell yourself: there is no miracle in this world, only your own efforts track; There is no luck in this world, only the courage to persevere.
About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.