二叉树day9

617. 合并二叉树

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        return prevOrder(root1, root2);
    }
    private TreeNode prevOrder(TreeNode root1, TreeNode root2) {
        if (root2 == null && root1 == null) return null;
        if (root1 == null && root2 != null) return root2;
        if (root1 != null && root2 == null) return root1;
        TreeNode root = new TreeNode(root2.val + root1.val);
        root.left = prevOrder(root1.left, root2.left);
        root.right = prevOrder(root1.right, root2.right);
        return root;
    }
}

 

700. 二叉搜索树中的搜索

//迭代前序
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        Deque<TreeNode> stack = new LinkedList<>();
        if (root != null) stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if (cur.val == val) return cur;
            if (cur.right != null) stack.push(cur.right);
            if (cur.left != null) stack.push(cur.left);
        }
        return null;
    }
}

上述不知道搜索树的特点:

改进如下:

//迭代
class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        Deque<TreeNode> stack = new LinkedList<>();
        if (root != null) stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if (cur.val == val) return cur;
            if (cur.val > val && cur.left != null) stack.push(cur.left);
            if (cur.val < val && cur.right != null) stack.push(cur.right);
        }
        return null;
    }
}

参考:programmercarl.com

posted @ 2022-04-05 21:26  一梦两三年13  阅读(27)  评论(0)    收藏  举报