遍历二叉树
public static class TreeNode{static List qianxu = new ArrayList<>();static List zhongxu = new ArrayList<>();static List houxu = new ArrayList<>();public static void main(String[] args) {/*** 0* 1 2* 3 4 8 9* 5 6 10 7*/Tree tree = new Tree(0);Tree a = new Tree(1);Tree b = new Tree(2);Tree c = new Tree(3);Tree d = new Tree(4);Tree e = new Tree(5);Tree f = new Tree(6);Tree g = new Tree(7);Tree h = new Tree(8);Tree i = new Tree(9);Tree j = new Tree(10);tree.left = a;tree.right = b;a.left = c;a.right = d;c.left = e;c.right = f;d.right = g;b.left = h;b.right = i;d.left = j;List list = houxu(tree);for(int q =0;q<list.size();q++){System.out.print(list.get(q)+" ");}//cengci(tree);}/*** 前序遍历 中 左 右* @param node* @return*/public static List qianxu(Tree node){qianxu.add(node.val);if(node.left != null){qianxu(node.left);}if(node.right != null){qianxu(node.right);}return qianxu;}/*** 中序遍历 左 中 右* @param node* @return*/public static List zhongxu(Tree node){if(node.left != null){zhongxu(node.left);}zhongxu.add(node.val);if(node.right != null){zhongxu(node.right);}return zhongxu;}/*** 后序遍历 左 右 中* @param node* @return*/public static List houxu(Tree node){if(node.left != null){houxu(node.left);}if(node.right != null){houxu(node.right);}houxu.add(node.val);return houxu;}}
层级遍历
/*** 层次遍历* @param node*/public static void cengci(Tree node){ArrayDeque<Tree> queue = new ArrayDeque<>(20);//首先将根节点加入栈中queue.add(node);//遍历二叉树while (!queue.isEmpty()) {//pop()函数和poll()函数都是从首位置取元素并删除;//区别在于,pop遇到null会报异常。poll遇到null会返回null。Tree tempNode = queue.poll();System.out.print(tempNode.val + " ");if(tempNode.left != null){queue.add(tempNode.left);}if(tempNode.right != null){queue.add(tempNode.right);}}}
二叉搜索树的最近公共祖先
// 235. 二叉搜索树的最近公共祖先public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(p.val == root.val){return p;}if(q.val == root.val){return q;}if(p.val > root.val && q.val > root.val){return lowestCommonAncestor(root.right,p,q);}else if(p.val < root.val && q.val < root.val){return lowestCommonAncestor(root.left,p,q);}else{return root;}}
数组转二叉树
思路:涉及二叉树时,一般使用递归
//108. 将有序数组转换为二叉搜索树
public TreeNode sortedArrayToBST(int[] nums) {
return buildTree(nums,0,nums.length-1);
}
private TreeNode buildTree(int[] nums,int l,int r){
if(l > r){
return null;
}
int n = l + (r-l)/2;
TreeNode root = new TreeNode(nums[n]);
root.left = buildTree(nums,l,n-1);
root.right = buildTree(nums,n+1,r);
return root;
}
