CodeTop100 Day21
今天这三题是二叉树中简单的题了,但也算是常考题
61、对称二叉树101
class Solution {public boolean isSymmetric(TreeNode root) {return ismirror(root,root);}public boolean ismirror(TreeNode t1,TreeNode t2){if(t1==null&&t2==null){return true;}if(t1==null||t2==null){return false;}return(t1.val==t2.val)&&ismirror(t1.left,t2.right)&&ismirror(t1.right,t2.left);} }
二叉树递归接口,传入两个起始节点开始遍历,判断null情况,只有两个节点同时为空才返回true,否则一旦有节点为空就返回false,判断传入节点是否相同就行了
62、二叉树的前序遍历144
class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> res=new ArrayList<>();dfs(res,root);return res;}void dfs(List<Integer> res,TreeNode root){if(root==null){return;}res.add(root.val);dfs(res,root.left);dfs(res,root.right);}
}
class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> res = new ArrayList<Integer>();if (root == null) {return res;}Deque<TreeNode> stack = new LinkedList<TreeNode>();TreeNode node = root;while (!stack.isEmpty() || node != null) {while (node != null) {res.add(node.val);stack.push(node);node = node.left;}node = stack.pop();node = node.right;}return res;}
}
迭代和递归写法都要会,迭代要注意,一直将根和左节点加入结果和栈中直到为空,然后再考虑右节点
63、二叉树的最大深度104
class Solution {public int maxDepth(TreeNode root) {if(root==null){return 0;}int left=maxDepth(root.left);int right=maxDepth(root.right);return Math.max(left,right)+1;}}
递归返回max(左子树最大深度,右子树最大深度)+1