LeetCode 94

题目链接
二叉树的中序遍历 - 力扣(LeetCode)​leetcode-cn.com图标
中序遍历的顺序是,左 根 右 这样子的顺序,题中的树的图形是
遍历过程先从左子树开始,左子树为空,回到父亲节点,输出1,接着到右子树的左子树这边,也就是3,输出3,再回到右子树的父亲节点2,输出2,树遍历结束后,输出的结果是
1 3 2,这是递归的写法。(看了官方的题解)
public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList arrayList = new ArrayList();
        auxiliary(root,arrayList);
        return arrayList;
    }

    /**
     * 递归的做法,中序遍历是 左根右
     */

    public void auxiliary(TreeNode root, ArrayList<Integer>arrayList){
        if (root != null){ // 遍历的前提是树和它的左右子树应该是不为空,如果为空,就不需要遍历了
                if (root.left != null){
                    auxiliary(root.left,arrayList);
                }
                arrayList.add(root.val); // 添加父节点
                 if (root.right != null){
                    auxiliary(root.right,arrayList);
                }
        }

    }

 


 
还有一种是用栈的方法,先保证树是不为空的,从根节点开始压入,接着压入树的左子树,再取出节点的值,右边同样这样处理。
    public List<Integer> inorderTraversal(TreeNode root) {

        ArrayList <Integer> arrayList = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || ! stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            arrayList.add(root.val);
            root = root.right;
        }
        return arrayList;
    }

 


参考资料
官方题解:二叉树的中序遍历 - 力扣(LeetCode)​leetcode-cn.com图标
博客园grandyang​www.cnblogs.com
 
posted @ 2019-08-05 11:45  WuCola  阅读(90)  评论(0)    收藏  举报