树Tree相关面试题

二叉树的层序遍历

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

import java.util.ArrayList;
import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
    ArrayList<ArrayList<Integer> > Print(TreeNode root) {
      if(root == null) {
          return ret;
      }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            ArrayList<Integer> tmp = new ArrayList<>();
            for(int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
        
    }
}

二叉树的层序遍历II(从下往上遍历)

https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ret = new LinkedList<>();
        if (root == null)
            return ret;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> tmp = new ArrayList<>();
            // 每次都取出一层的所有数据
            for (int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if (node.left != null){
                    queue.add(node.left);
                }                
                if (node.right != null){
                    queue.add(node.right);
                }     
            }
            // 每次都往队头塞
            ret.add(0, tmp);
        }
        return ret;
    }
}

二叉树的前序遍历

  • 递归
/**
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        pre(root, ret);
        return ret;
    }
    public void pre(TreeNode root, List<Integer> ret) {
        if(root == null) {
            return ;
        }
        ret.add(root.val);
        pre(root.left, ret);
        pre(root.right, ret);
    }
}
  • 迭代
/**
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        pre(root, ret);
        return ret;
    }
    public void pre(TreeNode root, List<Integer> ret) {
        if(root == null) {
            return;
        }
        Stack<TreeNode> stack=new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                ret.add(root.val);
                stack.add(root);
                root = root.left;
            }
            root = stack.pop().right;
        }
    }
}

二叉树的中序遍历

https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d?tpId=117&&tqId=38363&&companyId=665&rp=1&ru=/company/home/code/665&qru=/ta/job-code-high/question-ranking

  • 递归
//dfs
import java.util.*;
public class Solution {
    public List<Integer> list = new ArrayList<Integer>();
    public int[] inorderTraversal (TreeNode root) {
        in_order(root);
        int[] ret = new int[list.size()];
        for(int i = 0; i < list.size(); i++) {
            ret[i] = list.get(i);
        }
        return ret;
    }
    public void in_order(TreeNode root){
        if(root == null){
            return ;
        }else{
            in_order(root.left);
            list.add(root.val);
            in_order(root.right);
        }
    }
}
  • 迭代版本
//栈
public class Solution {
    public int[] inorderTraversal (TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
                if (cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                } else {
                    cur = stack.pop();
                    list.add(cur.val);
                    cur = cur.right;
                }
            }
        int[] ret = new int[list.size()];
        for(int i = 0; i < list.size(); i++) {
            ret[i] = list.get(i);
        }
        return ret;
    }
}

二叉树的后续遍历

  • 递归
/**
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        post(root, ret);
        return ret;
    }
    public void post(TreeNode root, List<Integer> ret) {
        if(root == null) {
            return ;
        }
        post(root.left, ret);
        post(root.right, ret);
        ret.add(root.val);
    }
}

**

  • 迭代版本

**

/**
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<Integer>();
        if(root == null) {
            return ret;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            if(node.left != null) {
                stack.push(node.left);//和传统先序遍历不一样,先将左结点入栈
            }
            if(node.right != null) {
                stack.push(node.right); //后将右结点入栈
            }
            ret.add(0, node.val);                        //逆序添加结点值
        }     
    return ret;
    }
}

实现二叉树先序,中序和后序遍历

https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362?tpId=117&&tqId=37819&&companyId=665&rp=1&ru=/company/home/code/665&qru=/ta/job-code-high/question-ranking

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    public int[][] threeOrders (TreeNode root) {
        // write code here
     // write code here
        List<Integer> preList = new ArrayList();
        List<Integer> midList = new ArrayList();
        List<Integer> afterList = new ArrayList();
         
        preOrder(root,preList);
        midOrder(root,midList);
        afterOrder(root,afterList);
         
        int len=preList.size();
        int [][]result=new int[3][len];
         
        for(int i=0;i<len;i++){
            result[0][i]=preList.get(i);
        }
        for(int i=0;i<len;i++){
            result[1][i]=midList.get(i);
        }
        for(int i=0;i<len;i++){
            result[2][i]=afterList.get(i);
        }
        return result;
    }
    //先序  中左右
    public void preOrder(TreeNode root,List<Integer> list){
        if(root==null){
            return;
        }
        list.add(root.val);
        preOrder(root.left,list);
        preOrder(root.right,list);
    }
    //中序  左中右
    public void midOrder(TreeNode root,List<Integer> list){
        if(root==null){
            return;
        }
        midOrder(root.left,list);
        list.add(root.val);
        midOrder(root.right,list);
    }
    //后序  左右中
    public void afterOrder(TreeNode root,List<Integer> list){
        if(root==null){
            return;
        }
         
        afterOrder(root.left,list);
        afterOrder(root.right,list);
        list.add(root.val);
    }
}

对称的二叉树

https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return dfs(root.left, root.right);
    }
    public boolean dfs(TreeNode p, TreeNode q) {
        if(p == null && q == null) {
            return true;
        }
        if(p == null || q == null) {
            return false;
        }
        return p.val == q.val && dfs(p.left, q.right) && dfs(p.right, q.left);
    }
}

二叉树的镜像

https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/

import java.util.*;
public class Solution {
    public TreeNode Mirror (TreeNode root) {
        // write code here
        if(root == null) {
            return null;
        }
        TreeNode left = Mirror(root.left);
        TreeNode right = Mirror(root.right);
        root.left = right;
        root.right = left;
        return root;
    }
}

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        Stack<TreeNode> stk = new Stack<TreeNode>();
        stk.push(root);
        while(!stk.isEmpty()) {
            TreeNode node = stk.pop();
            if(node.left != null) stk.push(node.left);
            if(node.right != null) stk.push(node.right);
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return root;
    }
}

合并二叉树

https://leetcode-cn.com/problems/merge-two-binary-trees/

import java.util.*;
public class Solution {
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        if(t1 == null)  return t2;
        if(t2 == null)  return t1;
        t1.val += t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        return t1;
    }
}

之字形打印二叉树I(左->右,左->右)

https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            ArrayList<Integer> tmp = new ArrayList<>();
            for(int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(tmp);
        } 
        return ret;
    }
}

之字形打印二叉树II(左->右->左)

问题链接:(https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/

/**
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            ArrayList<Integer> tmp = new ArrayList<>();
            for(int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                if(ret.size() % 2 == 0) {
                   tmp.add(node.val);
                }else {
                     tmp.add(0, node.val);
                }
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }
}

二叉树的最大深度

问题链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/

    //dfs
class Solution {
    public int maxDepth(TreeNode root) {
    if(root==null) return 0;
    int l=maxDepth(root.left);
    int r=maxDepth(root.right);
    return Math.max(l,r)+1;
    }
}
  //bfs
class Solution {
    public int maxDepth(TreeNode root) {
    if(root==null) return 0;
    Queue<TreeNode> queue=new LinkedList<>();
    queue.add(root);
    int ret=0;
    while(!queue.isEmpty())
    {
        ret++;
        for(int i=queue.size();i>0;i--)
        {
            TreeNode node=queue.poll();;
            if(node.left!=null) queue.add(node.left);
            if(node.right!=null) queue.add(node.right);
        }
    }
    return ret;
    }
}

平衡二叉树

问题链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/

//自顶向下dfs
class Solution {
   public boolean isBalanced(TreeNode root) {
        if(null == root){
            return true;
        }
        if(Math.abs(maxDepth(root.right)-maxDepth(root.left)) > 1){
            return false;
        }
        return isBalanced(root.right) && isBalanced(root.left);
    }
    public int maxDepth(TreeNode root) {
        if(null == root){
            return 0;
        }
        int l=maxDepth(root.left);
        int r=maxDepth(root.right);
        return Math.max(l,r)+1;
    }
}

//自底向上
class Solution {
    public int high(TreeNode root){
        if(root==null) return 0;
        int l=high(root.left);
        int r=high(root.right);
        if(Math.abs(l-r)<=1&&l!=-1&&r!=-1) 
        {
           return Math.max(l,r)+1;
        }else{
            return -1;
        }
    }
    public boolean isBalanced(TreeNode root) {
        return high(root)>=0;
    }
}

翻转一棵二叉树

问题链接:https://leetcode-cn.com/problems/invert-binary-tree/

//先序遍历
class Solution {
    public TreeNode invertTree(TreeNode root) {
     if(root==null) return null;
     //保存左子树
     TreeNode left=root.left;
     root.left=invertTree(root.right);
     root.right=invertTree(left);
     return root;
    }
}
//层序遍历
class Solution {
    public TreeNode invertTree(TreeNode root) {
        // 层次遍历--直接左右交换即可
        if (root == null) return null;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            TreeNode rightTree = node.right;
            node.right = node.left;
            node.left = rightTree;
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
        return root;
    }
}

二叉搜索树的第k大节点

https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/

class Solution {
    public int kthLargest(TreeNode root, int k) {
        if(root == null) {
            return -1;
        }
        List<Integer> list = new ArrayList<>();
        dfs(root, list);
        return list.get(list.size() - k);
    }
    public void dfs(TreeNode root, List<Integer> list) {
        if(root == null) {
            return ;
        }
        dfs(root.left, list);
        list.add(root.val);
        dfs(root.right, list);
    }
}


class Solution {
    private int ret = 0, count = 0;
    public int kthLargest(TreeNode root, int k) {
        if(root == null) {
            return -1;
        }
        dfs(root, k);
        return ret;
    }
    private void dfs(TreeNode root, int k) {
        if(root == null) return ;
        dfs(root.right, k);
        if(++count == k) {
            ret = root.val;
        }
        dfs(root.left, k);
    }
}

二叉搜索树的第k小元素

https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/

class Solution {
    public int kthSmallest(TreeNode root, int k) {
         if(root == null) {
            return -1;
        }
        List<Integer> list = new ArrayList<>();
        dfs(root, list);
        return list.get(k - 1);
    }
      public void dfs(TreeNode root, List<Integer> list) {
        if(root == null) {
            return ;
        }
        dfs(root.left, list);
        list.add(root.val);
        dfs(root.right, list);
    }
}


class Solution {
    private int ret = 0, count = 0;
    public int kthSmallest(TreeNode root, int k) {
        if(root == null) {
            return -1;
        }
        dfs(root, k);
        return ret;
    }
      private void dfs(TreeNode root, int k) {
        if(root == null) return ;
        dfs(root.left, k);
        if(++count == k) {
            ret = root.val;
        }
        dfs(root.right, k);
    }
}

二叉树根节点到叶子节点的所有路径和

https://www.nowcoder.com/practice/185a87cd29eb42049132aed873273e83?tpId=117&&tqId=37715&&companyId=898&rp=1&ru=/company/home/code/898&qru=/ta/job-code-high/question-ranking

public class Solution {

    public int sumNumbers (TreeNode root) {
        // write code here
        if(root == null) {
            return 0;
        }
        return func(root, 0);
    }
    public int func(TreeNode root, int sum) {
        if(root ==null){
            return 0;
        }
        sum = sum * 10 + root.val;
        if(root.left == null && root.right == null) {
            return sum;
        }
        return func(root.left, sum) + func(root.right, sum);
    }
}

二叉树中和为某一值的路径(一) Boolean类型

https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c?tpId=117&&tqId=37719&&companyId=665&rp=1&ru=/company/home/code/665&qru=/ta/job-code-high/question-ranking
迭代求解

import java.util.*;
/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
      if (root == null) {
          return false;
      }
        sum -= root.val;
        if (sum == 0 && root.left == null && root.right == null) {
            return true;
        }
            
        return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
    }
}

二叉树中和为某一指的路径(二)(回溯)

问题链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/

/**
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> ret = new ArrayList<>();
    public List<Integer> path = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        func(root, target);
        return ret;
    }
    public void func(TreeNode root, int target) {
        if(root == null) {
            return;
        }
        path.add(root.val);
        target -= root.val;
        if(target == 0 && root.left == null && root.right == null) {
            ret.add(new ArrayList(path));
        }
        func(root.left, target);
        func(root.right, target);
        path.remove(path.size() - 1);
    }
}

二叉搜索树和双向链表

问题链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof

  • 代码
class Solution {
    public Node prev=null;
    //中序遍历排序 并连接双向链表
    public  void inOrder(Node cur)
    {
        if(cur==null) return ;
            inOrder(cur.left);
            cur.left=prev;
            if(prev!=null)
            {
                prev.right=cur;
            }
            prev=cur;
            inOrder(cur.right);
        }
    
    public Node treeToDoublyList(Node root) {
        if(root==null) return null;
        inOrder(root);
        Node head=root;
        Node tail=root;
        //找头
        while(head.left!=null)
        {
            head=head.left;
        }
        //找尾
        while(tail.right!=null)
        {
            tail=tail.right;
        }
        //连接头和尾
        head.left=tail;
        tail.right=head;
        return head;
    }
}

二叉搜索树的最近公共祖先

https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) {
            return root;
        }
        if(p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor(root.left, p, q);
        }
        if(p.val > root.val && q.val > root.val) {
            return lowestCommonAncestor(root.right, p, q);
        }
        return root;
    }
}

二叉树的最近公共祖先

https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left == null) return right;
        if(right == null) return left;
        return root;
    }
}

在二叉树中找到两个节点的最近公共祖先

https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116?tpId=117&&tqId=37826&&companyId=665&rp=1&ru=/company/home/code/665&qru=/ta/job-code-high/question-ranking

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
       if(root == null) {
           return -1;
       }
        if(p == root.val || q == root.val) {
            return root.val;
        }
        int left = lowestCommonAncestor(root.left, p, q);
        int right = lowestCommonAncestor(root.right, p, q);
        if(left == -1) {
            return right;
        }
        if(right == -1) {
            return left;
        }
        return root.val;
    }
}

相同的树

问题链接:https://leetcode-cn.com/problems/same-tree/

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if((p == null && q != null) || (q == null && p != null)) return false;
        if(p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

另一颗树的子树(判断t1树中是否有与t2树完全相同的子树)

问题链接:https://leetcode-cn.com/problems/subtree-of-another-tree/submissions/

class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null || subRoot == null) return false;
       if(isSametree(root, subRoot)) return true;
       if(isSubtree(root.left, subRoot)) return true;
       if(isSubtree(root.right, subRoot)) return true;
         return false;
    }
    //判断两个树是否相同
    public boolean isSametree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if((p != null && q == null) || (p == null && q != null)) return false;
        if(p.val != q.val) return false;
        return isSametree(p.left, q.left) && isSametree(p.right, q.right);
    }
}

重建二叉树(前序中序构建二叉树)

public class Solution {
    public int preIndex;
    public TreeNode dfs(int[] pre, int[] in, int l, int r) {
        if(l > r) {
            return null;
        }
        TreeNode root = new TreeNode(pre[preIndex]);
        int index = findVal(in, pre[preIndex], l, r);
        preIndex++;
        root.left = dfs(pre, in, l, index - 1);
        root.right = dfs(pre, in, index + 1, r);
        return root;
        
    }
    public int findVal(int[] in, int key, int l, int r) {
        for(int i = l; i <= r; i++) {
            if(in[i] == key) {
                return i;
            }
        }
        return -1;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
           if(pre == null || in == null || pre.length == 0 || in.length == 0) {
               return null;
           } 
        return dfs(pre, in, 0, in.length - 1);
    }
}

中序后续遍历序列构建二叉树

https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

/**
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int posIndex = 0;
    public TreeNode buildTree(int[] ino, int[] pos) {
        if(ino == null || pos == null) return null;
        posIndex = pos.length-1;
        return dfs(ino, pos, 0, ino.length - 1);
    }
    public TreeNode dfs(int[] ino, int[] pos, int l, int r){
        if(l > r) return null;
        TreeNode root = new TreeNode(pos[posIndex]);
        int index = findVal(ino, pos[posIndex], l, r);
        posIndex--;
        root.right = dfs(ino, pos, index+1, r);
        root.left = dfs(ino, pos, l, index - 1);
        return root;
    }
    public int findVal(int[] ino, int key, int l, int r){
        for(int i = l; i <= r; i++)
        {
            if(ino[i] == key){
                return i;
            }
        }
         return -1;
    }
}

二叉树的右视图I

https://leetcode-cn.com/problems/binary-tree-right-side-view/

class Solution {
    List<Integer> ret = new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
                if(size - 1 == i) {
                    ret.add(node.val);
                }
            }
        }
        return ret;
    }
}

输出二叉树的右视图II

给前序和中序先重建树再输出右视图

import java.util.*;


public class Solution {
    public int preIndex;
    public ArrayList<Integer> ret = new ArrayList<>();
    public TreeNode createTree(int[] pre, int[] in, int l, int r) {
        if(l > r) {
            return null;
        }
        TreeNode root = new TreeNode(pre[preIndex]);
        int index = findVal(in, pre[preIndex], l, r);
        preIndex++;
        root.left = createTree(pre, in, l, index - 1);
        root.right = createTree(pre, in, index + 1, r);
        return root;
    }
    public int findVal(int[] in, int key, int l, int r) {
        for(int i = l; i <= r; i++) {
            if(in[i] == key) {
                return i;
            }
        }
        return -1;
    }
    public int[] solve (int[] pre, int[] in) {
       //西安将二叉树重建出来
        if(pre == null || in == null || pre.length == 0 || in.length == 0) {
            return null;
        }
        TreeNode root = createTree(pre, in, 0, in.length - 1);
        //在输出二叉树的右视图
        func(root);
        int[] ans = new int[ret.size()];
        for(int i = 0; i < ret.size(); i++) {
            ans[i] = ret.get(i);
        }
        return ans;
    }
    
    public ArrayList<Integer> func(TreeNode root) {
        if(root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
                if(size - 1 == i) {
                    ret.add(node.val);
                }
            }
        }
        return ret;
    }
}

二叉树根节点到叶子节点的所有路径和

public class Solution {
    public int sumNumbers (TreeNode root) {
        // write code here
        if(root == null) {
            return 0;
        }
        return func(root, 0);
    }
    public int func(TreeNode root, int sum) {
        if(root ==null){
            return 0;
        }
        sum = sum * 10 + root.val;
        if(root.left == null &&root.right == null) {
            return sum;
        }
        return func(root.left, sum) + func(root.right, sum);
    }
}

判断一棵二叉树是否为搜索二叉树和完全二叉树

https://www.nowcoder.com/practice/f31fc6d3caf24e7f8b4deb5cd9b5fa97?tpId=117&&tqId=37822&&companyId=665&rp=1&ru=/company/home/code/665&qru=/ta/job-code-high/question-ranking

import java.util.*;
public class Solution {
     public boolean[] judgeIt (TreeNode root) {
        boolean[] res = new boolean[2];
        res[0] = true; res[1] = true;
        if (root == null) return res;
        //res[0] = search(root, Long.MIN_VALUE, Long.MAX_VALUE);
        ArrayList<Integer> temp = new ArrayList<>();
        inorder(root, temp);
        for (int i = 0; i < temp.size() - 1; i++){
            if (temp.get(i) > temp.get(i + 1)) res[0] = false;
        }
        res[1] = all(root);        
        return res;
    }
    // 直接DFS返回钟中序遍历,再遍历temp判断
    void inorder(TreeNode root, ArrayList<Integer> temp){
        if (root == null) return;
        inorder(root.left, temp);
        temp.add(root.val);
        inorder(root.right, temp);    
    }
    //通过边界条件递归判断左右子树是否符合
//     boolean search(TreeNode root, long left, long right){
//         if (root == null) return true;
//         if (root.val > right || root.val < left) return false;
//         return search(root.left, left, root.val) && search(root.right, root.val, right);
//     } 
    boolean all(TreeNode root){
        if (root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        boolean flag = false;
        while(queue.size() != 0){            
            TreeNode newroot = queue.poll();
            TreeNode left = newroot.left;
            TreeNode right = newroot.right;
            if ( (left == null && right != null) || // 无左子树有右子树
                (flag && !(left == null && right == null)) ) //有残缺且非叶节点
                return false;
            if (left != null) queue.add(left);
            if (right != null) queue.add(right); 
            // 存在残缺节点
            if (left == null || right == null) flag = true;
        }
        return true;
    }
}

二叉树中的最大路径和

https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/

import java.util.*;
public class Solution {
    private int ret = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        /**
        对于任意一个节点, 如果最大和路径包含该节点, 那么只可能是两种情况:
        1. 其左右子树中所构成的和路径值较大的那个加上该节点的值后向父节点回溯构成最大路径
        2. 左右子树都在最大路径中, 加上该节点的值构成了最终的最大路径
        **/
        getMax(root);
        return ret;
    }
    
    private int getMax(TreeNode r) {
        if(r == null) {
            return 0;
        }
        int left = Math.max(0, getMax(r.left)); // 如果子树路径和为负则应当置0表示最大路径不包含子树
        int right = Math.max(0, getMax(r.right));
        ret = Math.max(ret, r.val + left + right); // 判断在该节点包含左右子树的路径和是否大于当前最大路径和
        return Math.max(left, right) + r.val;
    }
}

序列化二叉树

https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/

public class Codec {
   public String serialize(TreeNode root) {
    if(root == null){
        return "null,";
    }
        String res = root.val + ",";
        res += serialize(root.left);
        res += serialize(root.right);
        return res;
    }

    public TreeNode deserialize(String data) {
        String[] str = data.split(",");
        Queue<String> queue = new LinkedList<String>();
        for(int i = 0; i < str.length; i++){
            queue.offer(str[i]);
        }
        return createTree(queue);
    }

    public TreeNode createTree(Queue<String> queue){
        String val = queue.poll();
        f(val.equals("null")){
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(val));
        root.left = createTree(queue);
        root.right = createTree(queue);
        return root;
    }
}

持续更新中。。。。。。。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值