【二叉树part02】| 102.二叉树的层序遍历、226.翻转二叉树、101.对称二叉树

目录

✿LeetCode102.二叉树的层序遍历❀

 ✿LeetCode226.翻转二叉树❀

 ✿LeetCode101.对称二叉树❀


✿LeetCode102.二叉树的层序遍历❀

链接:102.二叉树的层序遍历

 

public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> result=new ArrayList<>();if(root==null){return result;}Queue<TreeNode> qu=new LinkedList<>();qu.offer(root);while(!qu.isEmpty()){List<Integer> list=new ArrayList<>();int size=qu.size();while(!qu.isEmpty() && size>0){TreeNode node=qu.poll();list.add(node.val);if(node.left!=null){qu.offer(node.left);}if(node.right!=null){qu.offer(node.right);}size--;}result.add(list);    }return result;}

 ✿LeetCode226.翻转二叉树❀

链接:226.翻转二叉树

 

public TreeNode invertTree(TreeNode root) {// 递归法if(root==null){return null;}TreeNode temp=invertTree(root.left);root.left=invertTree(root.right);root.right=temp;return root;}
public TreeNode invertTree(TreeNode root) {if(root==null){return null;}//    深度优先遍历Stack<TreeNode> st=new Stack<>();st.push(root);while(!st.isEmpty()){TreeNode node=st.pop();TreeNode temp=node.left;node.left=node.right;node.right=temp;if(node.right!=null){st.push(node.right);}if(node.left!=null){st.push(node.left);}}return root;}
public TreeNode invertTree(TreeNode root) {if(root==null){return null;}// 广度优先遍历Queue<TreeNode> qu=new LinkedList<>();qu.add(root);while(!qu.isEmpty()){int size=qu.size();while(!qu.isEmpty() && size>0){TreeNode node=qu.poll();TreeNode temp=node.left;node.left=node.right;node.right=temp;if(node.left!=null){qu.add(node.left);}if(node.right!=null){qu.add(node.right);}size--;}}return root;}

 ✿LeetCode101.对称二叉树❀

链接:101.对称二叉树

 

public boolean isSymmetric(TreeNode root) {// 树中节点数目在范围 [1, 1000] 内return compare(root.left,root.right);}public boolean compare(TreeNode left,TreeNode right){if(left==null && right !=null){return false;}else if(left!=null && right==null){return false;}else if(left==null && right==null){return true;}else{if(left.val!=right.val){return false;}}boolean outside=compare(left.left,right.right);boolean inside=compare(left.right,right.left);return outside && inside;}

本文链接:https://my.lmcjl.com/post/2189.html

展开阅读全文

4 评论

留下您的评论.