Given a binary tree, return the preorder traversal of its nodes ' values.
For example:
Given binary Tree {1,#,2,3} ,
1 2 / 3
Return [1,2,3] .
Binary tree pre-sequence traversal, root node → left subtree → right sub-tree
Problem solving idea One:
Recursive implementation, Java implementation is as follows:
Public list<integer> preordertraversal (TreeNode root) {list<integer> List = new Arraylist<integer> () ; if (root = null) return List;list.add (Root.val); List.addall (Preordertraversal (Root.left)); List.addall ( Preordertraversal (Root.right)); return list; }
Two ways to solve problems:
Using the stack implementation, the Java implementation is as follows:
Public list<integer> preordertraversal (TreeNode root) {list<integer> List = new Arraylist<integer> () ; if (root = null) return list; stack<treenode> stack = new stack<treenode> (); Stack.push (root); TreeNode pop = Root;while (!stack.isempty ()) {pop = Stack.pop (); List.add (pop.val); if (pop.right! = null) Stack.add ( Pop.right); if (pop.left! = null) Stack.add (pop.left);} return list;}
Java for Leetcode 144 Binary Tree Preorder traversal