原文链接http://www.myexception.cn/program/1958647.html
题目
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
return [1,2,3].
解1(递归)
//前序遍历 递归
public static void preorderTraversal(TreeNode root){
if(root==null) return ;
System.out.print(root.val+" ");
inorderTraversal(root.left);
inorderTraversal(root.right);
}
解2(非递归方法)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
Stack<TreeNode> nodeStack=new Stack<>();
while(true)
{
while(root!=null)
{
res.add(root.val);
nodeStack.push(root);
root=root.left;
}
if(nodeStack.isEmpty()) break;
TreeNode tempNode=nodeStack.pop();
root=tempNode.right;
}
return res;
}
}
解3(非递归)
//前序遍历 非递归
public static List<TreeNode> preorderTraversal2(TreeNode root){
List<TreeNode> tList=new ArrayList<TreeNode>();
Stack<TreeNode> tStack=new Stack<TreeNode>();
tStack.push(root);
while(!tStack.isEmpty()){
TreeNode p=tStack.pop();
tList.add(p);
System.out.print(p.val+" ");
if(p.right!=null) tStack.push(p.right);
if(p.left!=null) tStack.push(p.left);
}
return tList;
}