94. 二叉树的中序遍历

 

 

 

 

 

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        inorder(root, list);
        return list;
    }
    public void inorder(TreeNode root, List<Integer> list)
    {
        if (root == null)
        {
            return;
        }
        inorder(root.left,list);
        list.add(root.val);
        inorder(root.right,list);
    }
}

  

 

迭代

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Stack<TreeNode> stk = new Stack<TreeNode>();
        while (root != null || !stk.isEmpty())
        {
            while (root != null)
            {
                stk.push(root);root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}

  

posted on 2021-07-11 15:04  Hebye  阅读(16)  评论(0编辑  收藏  举报

导航