数据结构之二叉树(1)

题目描述

1、输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路
(1) 首先设置标志位result = false,因为一旦匹配成功result就设为true,剩下的代码不会执行,如果匹配不成功,默认返回false
(2) 递归思想,如果根节点相同则递归调用DoesTree1HaveTree2(),如果根节点不相同,则判断tree1的左子树和tree2是否相同,再判断右子树和tree2是否相同
(3) 注意null的条件,HasSubTree中,如果两棵树都不为空才进行判断,DoesTree1HasTree2中,如果Tree2为空,则说明第二棵树遍历完了,即匹配成功,tree1为空有两种情况(1)如果tree1为空&&tree2不为空说明不匹配,(2)如果tree1为空,tree2为空,说明匹配。

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

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

    }
    */
public class Solution {
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean result = false;
        if(root1 != null && root2 != null) {
            //判断根节点是否相同,如果相同则调用DoesTree1HaveTree2()
            if(root1.val == root2.val){
                result = DoesTree1HasTree2(root1, root2);
            }
            //判断和root1的左子树是否相同
            if(!result)
                result = HasSubtree(root1.left, root2);
            //判断是否和root1的右子树是否相同
            if(!result)
                result = HasSubtree(root1.right, root2);
        }
        return result;
    }
    public boolean DoesTree1HasTree2(TreeNode root1, TreeNode root2){
        if(root1 == null && root2 != null) return false;
        if(root2 == null) return true;
        if(root1.val != root2.val) return false;
        return DoesTree1HasTree2(root1.right,root2.right) && DoesTree1HasTree2(root1.left,root2.left);
    }
}
}

2、操作给定的二叉树,将其变换为源二叉树的镜像。
这里写图片描述

思路:
1、首先判断给定的二叉树是否为空,若为空return,若左子树为空且右子树为空return。
2、左子树、右子树互换;
3、递归操作左子树;
4、递归操作右子树;

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

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

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null)
            return;
        if(root.left == null && root.right == null)
            return;
        TreeNode Node_temp  = root.right;
        root.right = root.left;
        root.left = Node_temp;
        if(root.left != null)
            Mirror(root.left);
        if(root.right != null)
            Mirror(root.right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值