二叉树的遍历:
力扣104,111,二叉树的最大深度与最小深度求解,迭代与递归。
1.最大深度
迭代法:if(root==null){return res;}TreeNode temp=root;Stack<TreeNode> stack = new Stack<>();while (temp!=null||!stack.isEmpty()){if(temp!=null){stack.push(temp);temp=temp.left;}else{temp=stack.pop();res.add(temp.val);temp=temp.right;}}递归法:if(root==null){return 0;}int leftDepth=maxDepth(root.left);int rightDepth=maxDepth(root.right);return Math.max(leftDepth,rightDepth)+1;
2.最小深度
迭代法if(root==null){return 0;}Deque<TreeNode>queue = new LinkedList<>();queue.addLast(root);int res=0;while (!queue.isEmpty()){int size=queue.size();for(int i=0;i<size;i++){TreeNode node = queue.pollFirst();if(node.left==null&&node.right==null){return res+1;}if(node.left!=null){queue.addLast(node.left);}if(node.right!=null){queue.addLast(node.right);}}res++;}return res;递归法if(root==null){return 0;}int leftDepth=minDepth(root.left);int rightDepth=minDepth(root.right);if(root.left!=null&&root.right==null){return 1+leftDepth;}else if(root.left==null&&root.right!=null){return 1+rightDepth;}else{return 1+Math.min(leftDepth,rightDepth);}
