题目描述
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion
来源:牛客网
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion 来源:牛客网 boolean isSymmetrical(TreeNode pRoot) { if(pRoot == null) return true; return isSymmetrical(pRoot.left, pRoot.right); } private boolean isSymmetrical(TreeNode left, TreeNode right) { if(left == null && right == null) return true; if(left == null || right == null) return false; return left.val == right.val //为镜像的条件:左右节点值相等 && isSymmetrical(left.left, right.right) //2.对称的子树也是镜像 && isSymmetrical(left.right, right.left); }
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion
来源:牛客网
//===================非递归算法,利用DFS和BFS=============================//
/*
* DFS使用stack来保存成对的节点
* 2.确定入栈顺序,每次入栈都是成对成对的,如left.left, right.right ;left.rigth,right.left
*/
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion 来源:牛客网 boolean isSymmetricalDFS(TreeNode pRoot) { if(pRoot == null) return true; Stack<TreeNode> s = new Stack<>(); s.push(pRoot.left); s.push(pRoot.right); while(!s.empty()) { TreeNode right = s.pop();//成对取出 TreeNode left = s.pop(); if(left == null && right == null) continue; if(left == null || right == null) return false; if(left.val != right.val) return false; //成对插入 s.push(left.left); s.push(right.right); s.push(left.right); s.push(right.left); } return true; }
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion
来源:牛客网
/*
* BFS使用Queue来保存成对的节点,代码和上面极其相似
* 2.确定入队顺序,每次入队都是成对成对的,如left.left, right.right ;left.rigth,right.left
*/
链接:https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion 来源:牛客网 boolean isSymmetricalBFS(TreeNode pRoot) { if(pRoot == null) return true; Queue<TreeNode> s = new LinkedList<>(); s.offer(pRoot.left); s.offer(pRoot.right); while(!s.isEmpty()) { TreeNode left= s.poll();//成对取出 TreeNode right= s.poll(); if(left == null && right == null) continue; if(left == null || right == null) return false; if(left.val != right.val) return false; //成对插入 s.offer(left.left); s.offer(right.right); s.offer(left.right); s.offer(right.left); } return true; }
解题相关答案:
https://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb?f=discussion