Binary Tree Preorder Traversal

来源:互联网 发布:ubuntu mysql安装路径 编辑:程序博客网 时间:2024/04/30 09:59

Binary Tree Preorder Traversal

 Total Accepted: 26399 Total Submissions: 74449My Submissions

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].

Note: Recursive solution is trivial, could you do it iteratively?

Have you been asked this question in an interview? 

Discuss

这个以前练习的很熟,现在竟然快写不出来了。先序遍历,简单方法就使用两个while循环,开头的while循环一栈大小为条件,内层循环以当前

节点是否为空为条件。内层循环的内容是一直想左移动,并把节点入栈。先序的话,就是一边向左走,一边存入节点栈,并把节点的值也存进来。

内层循环跳出来之后,节点栈会有一个空的节点,需要拿出来。这里有一个疑问,就是,内层循环总是向左走,会不会总是在打印左子树的值。

其实不会,因为这个处理在跳出内层循环后,让栈顶的节点弹出,并把栈顶节点的右节点入栈。如果只有左子树,那么所有节点的右子树为空。那么内层循环只会执行一次,其余情况都无法进入循环体。这就是两层循环写法的其妙值处。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */  public class Solution {    public ArrayList<Integer> preorderTraversal(TreeNode root) {        ArrayList<Integer> res = new ArrayList<Integer>();        List<TreeNode> stack = new ArrayList<TreeNode>();        TreeNode tmp,node;        if(root==null)        {        return res;        }       // stack.add(tmp);       //res.add(tmp.val);       stack.add(root);        tmp = root;        while(stack.size()>0)        {        whilde(tmp!=null)        {        res.add(tmp.val);        tmp = tmp.left;        stack.add(tmp);        }        stack.remove(stack.size()-1);        if(stack.size()>0)        {        tmp = stack.get(stack.size()-1);        stack.remove(stack.size()-1);        tmp = tmp.right;        stack.add(tmp);        }        }        return res;    }}
单层循环的写法,初始条件不同,外层循环的判断条件也有点不一样。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */  public class Solution {    public ArrayList<Integer> preorderTraversal(TreeNode root) {        ArrayList<Integer> res = new ArrayList<Integer>();        List<TreeNode> stack = new ArrayList<TreeNode>();        TreeNode tmp,node;        if(root==null)        {        return res;        }       //stack.add(root);        tmp = root;        while(stack.size()>0||tmp!=null)        {            if(tmp!=null)            {                res.add(tmp.val);                stack.add(tmp);                tmp = tmp.left;            }else            {                tmp = stack.get(stack.size()-1);                stack.remove(stack.size()-1);                tmp = tmp.right;            }        }        return res;    }}



0 0