In a binary tree, the root node is at depth
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the
Return
0, and children of each depth k node is at a depth k+1.Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the
root of a binary tree with unique values, and the values x and y of two different nodes in the tree.Return
true if and only if the nodes corresponding to the values x and y are cousins.Example 1:
Input: root ={1,2,3,4}, x = 4, y = 3
Output: falseApproach
Java
public class CousinsInBinaryTree {public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.right = new TreeNode(4);root.right.right = new TreeNode(5);int x = 5, y = 4;System.out.println(isCousins(root, x, y));}static int parentx;static int parenty;static int height(TreeNode root, int x, int level) {if (root == null)return 0;if (root.val == x)return level;parentx = root.val;int h1 = height(root.left, x, level + 1);if (h1 != 0)return h1;parentx = root.val;return height(root.right, x, level + 1);}static boolean isCousins(TreeNode root, int x, int y) {parentx = -1;parenty = -1;if (root.val == x || root.val == y)return false;int h1 = height(root, x, 0);parenty = parentx;parentx = -1;int h2 = height(root, y, 0);if (h1 == h2 && parentx != parenty)return true;return false;}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};int height(TreeNode *root,int x,int &parent,int level){if(root==NULL)return 0;if(root->data==x)return level;parent=root->data;int h1=height(root->left,x,parent,level+1);if(h1!=0)return h1;parent=root->data;return height(root->right,x,parent,level+1);}bool isCousins(TreeNode* root, int x, int y){int parentx=-1;int parenty=-1;if(root->data==x || root->data==y)return false;int h1=height(root,x,parentx,0);int h2=height(root,y,parenty,0);if(h1==h2&&parentx!=parenty)return true;return false;}int main(){TreeNode *root=new TreeNode(1);root->left=new TreeNode(2);root->right=new TreeNode(3);root->left->left=new TreeNode(4);int x=4,y=3;if(isCousins(root,x,y))cout<<"true";elsecout<<"false";return 0;}
No comments:
Post a Comment