How to understand the preorder traversal of python binary tree
How to understand the preorder traversal of python binary tree? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
1. Brief introduction of the problem.
Given a binary tree, return its preorder traversal.
2, example
Example:
Input: [1\ 2 / 3] 1\ 2 / 3
Output: [1Jing 2jue 3] Advanced: recursive algorithm is very simple, can you do it through iterative algorithm?
3, the train of thought of solving the problem
Use recursion to solve the problem
4, problem solving procedure
Import java.util.ArrayList;import java.util.List;import java.util.Stack
Public class PreorderTraversalTest2 {public static void main (String [] args) {TreeNode T1 = new TreeNode (1); TreeNode T2 = new TreeNode (2); TreeNode T3 = new TreeNode (3); t1.right = T2; t2.left = T3; List list = preorderTraversal (T1); System.out.println ("list =" + list)
}
Private static List list = new ArrayList ()
Public static List preorderTraversal (TreeNode root) {if (root = = null) {return list;} dfs (root); return list;}
Private static void dfs (TreeNode root) {list.add (root.val); if (root.left! = null) {dfs (root.left);} if (root.right! = null) {dfs (root.right);}
5. Picture version of the problem solving program.
After reading the above, have you mastered how to understand the preorder traversal of the python binary tree? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!