700. 二叉搜索树中的搜索
问题描述:
代码:
class Solution { public TreeNode searchBST(TreeNode root, int val) { TreeNode t = new TreeNode(); Queue<TreeNode> tree = new LinkedList<>(); tree.offer(root); while(!tree.isEmpty()){ t=tree.poll(); if(t.val==val) return t; if(t.left!=null) tree.offer(t.left); if(t.right!=null) tree.offer(t.right); } return null; } }
思路:
层序遍历
701. 二叉搜索树中的插入操作
问题描述:
代码:
class Solution { public TreeNode insertIntoBST(TreeNode root, int val) { TreeNode t = new TreeNode(); TreeNode v = new TreeNode(val); if(root==null) root=v; Queue<TreeNode> tree = new LinkedList<>(); tree.offer(root); while(!tree.isEmpty()){ t=tree.poll(); if(t.val<v.val) { if(t.right==null){ t.right=v; }else{ tree.offer(t.right); } } if(t.val>v.val){ if(t.left==null){ t.left=v; }else{ tree.offer(t.left); } } } return root; } }
思路:
层序遍历