Binary Tree Preorder Traversal
Problem:
Given a binary tree, return the preorder traversal of its nodes ' values.
Recursive solution is trivial, could do it iteratively?
Ideas:
Stack method pops up the top of the stack when a node is added to do the node until the stack empty
My Code:
Public classSolution { PublicList<integer>preordertraversal (TreeNode root) {List<Integer> list =NewArraylist<integer>(); if(Root = =NULL)returnlist; Stack<TreeNode> stack =NewStack<treenode>(); Stack.push (root); Do{TreeNode node=Stack.pop (); List.add (Node.val); if(Node.right! =NULL) Stack.push (node.right); if(Node.left! =NULL) Stack.push (node.left); } while(!stack.isempty ()); returnlist; }}View Code
Others code:
Public classSolution { PublicList<integer>preordertraversal (TreeNode root) {Stack<TreeNode> stack =NewStack<treenode>(); List<Integer> preorder =NewArraylist<integer>(); if(Root = =NULL) { returnpreorder; } stack.push (root); while(!Stack.empty ()) {TreeNode node=Stack.pop (); Preorder.add (Node.val); if(Node.right! =NULL) {Stack.push (node.right); } if(Node.left! =NULL) {Stack.push (node.left); } } returnpreorder; }}View Code
The Learning Place:
- A binary tree is a tree with two forks finding the tree is satisfying the left subtree < node < right subtree two fork balance tree Saozi The height difference between the right sub-tree is 1
Binary Tree Preorder Traversal