How to return the middle order traversal of python binary tree
Today, I will talk to you about how to return to the middle order traversal of the python binary tree, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
1. Given a binary tree, return its mid-order traversal.
2, example
Example:
Input: [1\ 2 / 3] 1\ 2 / 3
Output: [1] Advanced: recursive algorithm is very simple, can you do it through iterative algorithm?
3, the train of thought of solving the problem
Here are two ways to solve the problem, one is to solve it recursively, and the other is to use iterative method.
4, problem solving procedure
Import java.util.ArrayList;import java.util.List;import java.util.Stack
Public class InorderTraversalTest2 {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 = inorderTraversal2 (T1); System.out.println ("list =" + list)
}
Private static List list = new ArrayList ()
Public static List inorderTraversal (TreeNode root) {if (root = = null) {return list;} dfs (root); return list;}
Private static void dfs (TreeNode root) {
If (root.left! = null) {dfs (root.left);} list.add (root.val); if (root.right! = null) {dfs (root.right);}}
Public static List inorderTraversal2 (TreeNode root) {if (root = = null) {return list;} Stack stack = new Stack (); TreeNode tempNode = root; while (! stack.isEmpty () | | tempNode! = null) {while (tempNode! = null) {stack.push (tempNode); tempNode = tempNode.left } TreeNode temp = stack.pop (); list.add (temp.val); tempNode = temp.right
} return list;}}
5. Picture version of the problem solving program.
According to the characteristics of the binary tree to do it, the use of recursion is much faster than the use of iteration in time consumption, the use of recursion uses the way of system stack to write, the way of iteration is to use the stack structure created by oneself.
After reading the above, do you have any further understanding of how to return the middle order traversal of the python binary tree? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.