相同的树

leetcode100题:相同的树

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

相同的树

相同的树

相同的树
求解:

 // Definition for a binary tree node.
  public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
 
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        
        //判断是否有空树
        if(p==null && q==null){
            return true;
        }
        //左右节点分别递归判断
        if(p != null && q != null && q.val == p.val){
            return isSameTree(p.left,q.left) && isSameTree(p.right,q.right); 
        }else{
            return false;
        }
        
    }
}

总结

这是一道和树这种数据结构有关的一道leetcode上的题目,知识点个人认为是树的遍历这一块,借助这一道题目复习复习二叉树的前中后序遍历

递归形式的遍历实现比较简单,就不写出来了,主要想复习复习非递归方式遍历

前序遍历

private static void preOrder(TreeNode root){
	
	ArrayList<T> list = new ArrayList<>();
	Stack<TreeNode> stack = new Stack<>();
	if(root != null){
		stack.push(root);
		while(!stack.isEmpty()){
			TreeNode node = stack.pop();
			list.add(node.val);
			if(node.right != null){
				stack.push(node.right);
			}
			if(node.left != null){
				stack.push(node.left);
			}
		}
	}
	for(T i : list){
		System.out.println(i+"\t");
	}	
}

中序遍历

private static void order(TreeNode root){
	ArrayList<T> list = new ArrayList<>();
	Stack<TreeNode> stack = new Stack<>();
	while(root != null || !stack.isEmpty()){
		if(root != null){
			stack.push(root);
			root = root.left;
		}else{
			root = stack.pop();
			list.add(root.val);
			root = root.right;
		}
	}
	for(T i : list){
		System.out.println(i+"\t");
	}	
}

后序遍历

private static void order(TreeNode root){
	ArrayList<T> list = new ArrayList<>();
	Stack<TreeNode> stack = new Stack<>();
	Stack<TreeNode> resultStack = new Stack<>();
	while(root != null || !stack.isEmpty()){
		if(root != null){
			stack.push(root);
			resultStack.push(root);
			root = root.right;
		}else{
			root = stack.pop();
			root = root.left;
		}
	}
	while(!resultStack.isEmpty()){
		list.add(resultStack.pop().val);
	}
	for(T i : list){
		System.out.println(i+"\t");
	}	
}