二叉树遍历
前序遍历 中序遍历 后续遍历
代码 前 中 后序遍历
package Trww;public class TreeTraversal {/*12 34 5 6*/public static void main(String[] args) {TreeNode tree = new TreeNode(new TreeNode(new TreeNode(4),2,null),1,new TreeNode(new TreeNode(5),3,new TreeNode(6)));preOrder(tree);System.out.println();inorder(tree);System.out.println();postOrder(tree);}
// 前序遍历static void preOrder(TreeNode node){if (node==null){return;}System.out.print(node.val+"\t");//值preOrder(node.left);preOrder(node.right);}
// 中序遍历static void inorder(TreeNode node){if (node==null){return;}inorder(node.left);System.out.print(node.val+"\t");//值inorder(node.right);}
// 后续遍历static void postOrder(TreeNode node){if (node==null){return;}postOrder(node.left);postOrder(node.right);System.out.print(node.val+"\t");//值}
}
对称二叉树
https://leetcode.cn/problems/symmetric-tree/description/
package Trww;public class E04Leetcode101 {public boolean isSymmetric(TreeNode root) {return check(root.left,root.right);}private boolean check(TreeNode left,TreeNode right){if (left==null && right==null){return true;}//判断左右是否为空有一个为空就不对if (right==null||left==null){return false;}//判断里面值if (left.val!=right.val){return false;}//左孩子的左边左孩子和右边的右孩子return check(left.left,right.right) &&check(left.right,right.left);}}
二叉树的最大深度
package Trww;public class E04Leecode104 {static int left=0;static int right=0;public static void main(String[] args) {TreeNode treeNode2 = new TreeNode(3);TreeNode treeNode = new TreeNode(9,treeNode2,treeNode2);System.out.println(maxDepth(treeNode));}static int maxDepth(TreeNode root) {if (root==null){return 0;}int d1 =maxDepth(root.left);int d2 =maxDepth(root.right);return Integer.max(d1,d2)+1;}
}