Binary Tree Preorder Traversal && Binary Tree Postorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
Given a binary tree, return the postorder traversal of its nodes' values.
对于一棵二叉树的前序和后序遍历来说,应该很熟悉了。在这里采用的是递归的方法。
如果不在IDE里面编辑的话,貌似还真是不习惯。有一些零星的小错误。
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root)
{
ArrayList<Integer> preorder = new ArrayList<Integer>();
if(root == null)return preorder;
visit(root,preorder);
return preorder;
}
public void visit(TreeNode root,ArrayList<Integer> order)
{
if(root == null)return;
order.add(root.val);
if(root.left != null)
{
visit(root.left,order);
}
if(root.right != null)
{
visit(root.right,order);
}
}
}
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> postorder = new ArrayList<Integer>();
if(root == null) return postorder;
visit(root,postorder);
return postorder;
}
public void visit(TreeNode root,ArrayList<Integer> order)
{
if(root == null)return;
TreeNode start = root;
if(start.left != null)
{
visit(start.left,order);
}
if(start.right != null)
{
visit(start.right,order);
}
order.add(start.val);
}
}