class Solution {
public void tree2strChild(TreeNode t, StringBuilder sb) {
if (t == null) return;
sb.append (t.val);
if (t.left == null){
if (t.right == null) {
return;
}else{
sb.append("()");
}
}else{
sb.append("(");
tree2strChild(t.left,sb);
sb.append(")");
}
if (t.right == null){
return;
}else {
sb.append("(");
tree2strChild(t.right,sb);
sb.append(")");
}
}
public String tree2str(TreeNode root) {
if (root == null) return null;
StringBuilder sb = new StringBuilder();
tree2strChild(root,sb);
return sb.toString();
}
}
class Solution {
public int pi = 0;
public TreeNode buildTreeChild(int [] postorder,int []inorder,int begin,int end) {
if (begin > end) return null;
TreeNode root = new TreeNode(postorder[pi]);
int ri = findIndex(inorder,begin,end,postorder[pi]);
pi --;
root.right = buildTreeChild(postorder,inorder,ri+1,end);
root.left = buildTreeChild(postorder,inorder,begin,ri-1);
return root;
}
public int findIndex(int []inorder,int begin,int end,int key) {
for (int i = 0 ; i <= end ; i++) {
if (inorder[i] == key) {
return i;
}
}
return -1;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
pi = postorder.length -1;
return buildTreeChild(postorder,inorder,0,inorder.length -1);
}
}
JZ36 二叉搜索树与双向链表(牛客网)
public class Solution {
TreeNode prev = null;
public void ConvertChild(TreeNode pCur) {
if (pCur == null) return;
ConvertChild(pCur.left);
pCur.left = prev;
if (prev != null) {
prev.right = pCur;
}
prev = pCur;
ConvertChild(pCur.right);
}
public TreeNode Convert(TreeNode pRootOfTree) {
if (pRootOfTree == null) return null;
ConvertChild(pRootOfTree);
TreeNode head = pRootOfTree;
while(head.left != null) {
head = head.left;
}
return head;
}
}
236. 二叉树的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (root == p || root == q) return root;
TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
if (leftTree != null && rightTree != null) return root;
if (leftTree != null ) return leftTree;
if (rightTree != null) return rightTree;
return null;
}
}
KY11 二叉树遍历
输入:
abc##de#g##f###
输出:
c b e g d f a
import java.util.*;
class TreeNode{
public char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
public class Main{
public static int i = 0;
public static TreeNode createTree(String str) {
TreeNode root = null;
if (str.charAt(i) != '#') {
root = new TreeNode(str.charAt(i));
i++;
root.left = createTree(str);
root.right = createTree(str);
}else {
i++;
}
return root;
}
public static void inOrdertraversal(TreeNode root) {
if (root == null) return ;
inOrdertraversal( root.left);
System.out.print(root.val+" ");
inOrdertraversal( root.right);
}
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
TreeNode root = createTree(str);
inOrdertraversal(root);
}
}
}