[leedcode 144] Binary Tree Preorder Traversal
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]
.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List<Integer> res; public List<Integer> preorderTraversal(TreeNode root) { /* //解法一:借助栈数据结构 List<Integer> res=new ArrayList<Integer>(); if(root==null) return res; Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode node=root; while(node!=null||!stack.isEmpty()){//条件 while(node!=null){ res.add(node.val);///先序 stack.push(node); node=node.left; } node=stack.pop(); //res.add(node.val);中序 node=node.right; } return res;*/ /*解法二: res=new ArrayList<Integer>(); preorder(root); return res; */ //解法三:此种解法注意push子节点的顺序,先右节点,再左节点 List<Integer> res=new ArrayList<Integer>(); Stack<TreeNode> stack=new Stack<TreeNode>(); if(root==null) return res; stack.push(root); while(!stack.isEmpty()){ TreeNode node=stack.pop(); res.add(node.val); if(node.right!=null){ stack.push(node.right); } if(node.left!=null){ stack.push(node.left); } } return res; } /*解法二: public void preorder(TreeNode node){ if(node==null) return; res.add(node.val); preorder(node.left); preorder(node.right); }*/ }