lintcode:二叉树的中序遍历

来源:互联网 发布:淘宝司法拍卖怎么样 编辑:程序博客网 时间:2024/04/30 15:16
/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param root: The root of binary tree.     * @return: Inorder in ArrayList which contains node values.     */    public ArrayList<Integer> inorderTraversal(TreeNode root) {        // write your code here        ArrayList<Integer> res=new ArrayList<Integer>();//记录遍历路径        ArrayList<TreeNode> p=new ArrayList<TreeNode>();//记录节点        while(root!=null||p.size()!=0){            while(root!=null){                p.add(root);                root=root.left;            }//如果root不为空一直像左走到底,root指向最左边的节点。若为空,则退到上一个节点            root=p.get(p.size()-1);            p.remove(p.size()-1);//取得元素并删除            res.add(root.val);            root=root.right;        }        return res;    }}
中序遍历:左 中 右
0 0
原创粉丝点击